2017-02-04 51 views
1

即時嘗試將我的角1指令代碼轉換爲角2.但它會拋出一個錯誤,指出ElementRef.find()不是函數。有沒有其他辦法可以達到同樣的效果。在元素中查找元素。ElementRef.find()不是函數angular 2

角1

link: function ($scope, $elem, attrs) { 
      var elem = $elem[0] table = $elem, 
       thead = table.find('thead'), 
       tbody = table.find('tbody'), 
     } 

角2

constructor(el: ElementRef, renderer: Renderer) { 
    this.elem = el.nativeElement; 
    this.table = el, 
    this.thead = this.table.find('thead'); 
    this.tbody = this.table.find('tbody'); 
    this.tableWidth = this.table[0].getBoundingClientRect().width; 
} 

回答

2

構造(私人EL:ElementRef,私人渲染:渲染器){}

//ngAfterContentInit() { // for directive or projected content 
ngAfterViewInit() { // for searching a components template 
    this.elem = el.nativeElement; 
    this.table = el, 
    this.thead = this.table.querySelector('thead'); 
    this.tbody = this.table.querySelector('tbody'); 
    this.tableWidth = this.table[0].getBoundingClientRect().width; 
} 

findjQuery。 Angular2中沒有包含jQuery

另請參見angular 2/typescript : get hold of an element in the template

+0

this.table裏面的angular 2指令docent顯示內部元素。所以querrySelector文件可以工作。甚至嘗試this.table.nativeElement.querySelector('thead') – janIreal23

+0

請提供更多的代碼。從這些微小的代碼片段中診斷髮生了什麼是不可能的。如果HTML位於組件的模板中,那麼您還需要將代碼從構造函數移動到「ngAfterViewInit()」;如果代碼位於指令中或其投影內容更新了我的答案,則需要將代碼從構造函數移動到ngAfterViewInit 。 –

+1

完美'this.table.nativeElement.querySelector('thead');''ngAfterViewInit()'內''工作。 – janIreal23

相關問題