javascriptjquerydirectiveangular5

Angular 5 - lifecycle hook in directive


I am new to Angular 5.
I have created the directive for the external JS library.
But in the same directive, I am binding value to the attribute.

I am trying to sue ngAfterViewInit to detect whether all the values are bound to the attribute and then call the jQuery plugin.

But I have find life cycle hook only for the component. Can I use those in directive? Is that a good choice?

<div *ngFor="let item of easypiechartOptions"
    [option]="item"
    appEasyPieChart
    [attr.data-percent]="item.percent">
</div>

If I don't use ngAfterViewInit, then when I call jQuery plugin, the values are not bound.
If I use that, the attribute values are ready when I call the jQuery plugin.


Solution

  • But I have find life cycle hook only for the component. Can I use those in directive? Is that a good choice?

    It seems that the hooks we use for components are intended also for directives. we can understand this concept from the docs, here.

    (form the docs :)

    A directive has the same set of lifecycle hooks, minus the hooks that are specific to component content and views

    Directive and component instances have a lifecycle as Angular creates, updates, and destroys them. Developers can tap into key moments in that lifecycle by implementing one or more of the lifecycle hook interfaces in the Angular core library

    there's an example of using the familiar hooks on a directive here