Angular 2 – How to get template reference variable or directive instance inside component

In this post let us see how to get Angular 2 directive/child component instance inside the parent component class.

ViewChild in action
The ViewChild decorator can be used to achieve this requirement.
The ViewChild accepts either the directive type or the template reference variable as argument and set the directive instance to the target property after the view get initiated.

@Component({
  selector: 'child-cmp',
  template: '

child

'
})
class ChildCmp {
  doSomething() {}
}
@Component({
  selector: 'some-cmp',
  template: '<child-cmp></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {
  @ViewChild(ChildCmp) child:ChildCmp;
  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

The ViewChild will set the target property once the component view get rendered hence accessing the property before the view get initiated will return inappropriate result.

You can use the ngViewAfterInit lifecycle hook to identify the view initialization.

Argument as Directive type vs template variable
Using argument as template variable ViewChild is best from my point of view as it will provide access to specific directive instance when having more than one directive in the template.

@Component({
  selector: 'some-cmp',
  template: '<child-cmp #child></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {
  @ViewChild('child') child:ChildCmp;
  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

Happy Scripting.. 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s