zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Angular] @ViewChild read custom directive and exportAs

Angular and Read Custom directive
2023-09-14 09:00:49 时间

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>