Angular 2: Get reference to a directive used in a component -
i have component template looks this:
<div [my-custom-directive]>some content here</div>
i need access mycustomdirective class instance used here. when want access child component, use ng.core.viewchild query. there equivalent feature access child directive?
you can use exportas
property of @directive
annotation. exports directive used in parent view. parent view, can bind view variable , access parent class using @viewchild()
.
example plunker:
@directive({ selector:'[my-custom-directive]', exportas:'customdirective' //the name of variable access directive }) class mycustomdirective{ logsomething(text){ console.log('from custom directive:', text); } } @component({ selector: 'my-app', directives:[mycustomdirective], template: ` <h1>my first angular 2 app</h1> <div #cdire=customdirective my-custom-directive>some content here</div> ` }) export class appcomponent{ @viewchild('cdire') element; ngafterviewinit(){ this.element.logsomething('text appcomponent'); } }
update
as mentioned in comments, there alternative above approach.
instead of using exportas
, 1 directly use @viewchild(mycustomdirective)
or @viewchildren(mycustomdirective)
here code demonstrate difference between 3 approaches:
@component({ selector: 'my-app', directives:[mycustomdirective], template: ` <h1>my first angular 2 app</h1> <div my-custom-directive>first</div> <div #cdire=customdirective my-custom-directive>second</div> <div my-custom-directive>third</div> ` }) export class appcomponent{ @viewchild('cdire') secondmycustomdirective; // second @viewchildren(mycustomdirective) allmycustomdirectives; //['first','second','third'] @viewchild(mycustomdirective) firstmycustomdirective; // first }
update
Comments
Post a Comment