[Angular] @ViewChild read custom directive and exportAs

For example we have a component:

<Card ></Card>

And a driective:

<Card highlighted></Card>

We want to get the driective instant inside the component code, we can use @ViewChild:

@ViewChild(CardComponennt, {read: HighlightedDirective}) highlighted: HighlightedDirective

Then we can access the instant in ngAfterViewInited lifecycle hook.

----- 

Another way to access driective is inside component template. we need to use 'exportAs' from  the directive:

@Directive({
   name: 'highlighted',
   exportAs: 'hl'
})

...

toggle () {...}

Inside the template, we can get it from the template reference:

<Card highlighted #hlref="hl"></Card>

<button (click)="hlref.toggle()"></button>
原文地址:https://www.cnblogs.com/Answer1215/p/10239473.html