2017-02-04 53 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

相关问题