1

im trying to convert my angular 1 directive code to angular 2. But it throws an error saying ElementRef.find() is not a function. is there any other way to achieve the same. to find element inside an element.

Angular 1

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

Angular 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;
}
Ireal
  • 355
  • 4
  • 16

1 Answers1

2

constructor(private el: ElementRef, private renderer: Renderer) {}

 //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;
 }

find is jQuery. There is no jQuery included in Angular2.

See also angular 2 / typescript : get hold of an element in the template

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • this.table inside the angular 2 directive docent show the inner elements. so the querrySelector docent work . even tried this.table.nativeElement.querySelector('thead') – Ireal Feb 04 '17 at 15:02
  • Please provide more code. It's impossible to diagnose what's going on from these tiny code fragments. You also need to move the code from the constructor to `ngAfterViewInit()` if the HTML is in the template of a component, or to `ngAfterContentInit()` if the code is in a directive or if its projected content - updated my answer. – Günter Zöchbauer Feb 04 '17 at 15:04
  • 1
    perfect `this.table.nativeElement.querySelector('thead');` inside `ngAfterViewInit()` worked. – Ireal Feb 04 '17 at 15:16