2016-12-02 80 views
4

我的Angular2應用程序使用RESTful API,然後根據結果創建一堆<select>元素。我試圖在這些<select>元素上調用jQuery函數,但它看起來像jQuery函數執行得太晚。我試着把這個功能放在ngAfterContentInit裏,但是那沒有奏效。把它放在ngAfterViewChecked凍結我的瀏覽器。Angular 2在渲染元素後調用jQuery - 使用API​​之後

頁面呈現後,如果我將jQuery功能粘貼到控制檯中,一切正常,所以我知道我的功能和一切都正常。他們的順序可能會搞砸了。

在我的組件:

ngOnInit() { 
    this.myService.getAll().subscribe(
      data => this._data = data, 
      error => this._error = "invalid."); 
} 

ngAfterViewInit() { 
    $("select").select2(); // <--- jQuery function I need to execute after rendering 
} 

在我的模板:

<select *ngFor="let d of _data">...blah blah</select> 
+0

怎麼樣調用'$(「選擇」)。select2();'在訂閱? –

+0

不幸運.. – 7ball

回答

7

這應該爲你工作:

@ViewChild('select') selectRef: ElementRef; 
constructor(private myService: MyService, private ngZone: NgZone) {} 

ngOnInit() { 
    this.myService.getAll().subscribe(data => { 
    this.options = data; 
    // waiting until select options are rendered 
    this.ngZone.onMicrotaskEmpty.first().subscribe(() => { 
     $(this.selectRef.nativeElement).select2(); 
    }); 
    }); 
} 

Plunker Example

+0

謝謝!這工作! – 7ball

+0

但是這不會影響1'