Reputation: 3249
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.
Upvotes: 5
Views: 11863
Reputation: 4535
All the life cycle methods is available in directive.
I created the custom-directive and added all the life cycle methods as
@Directive({
selector: '[appCustomDirective]'
})
export class CustomDirective implements OnInit, OnChanges, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy {
@Input() inputValue: string;
constructor() {
console.log('Constructor called');
}
ngOnInit(): void {
console.log('ngOnInit called');
}
ngOnChanges(changes: SimpleChanges): void {
console.log('ngOnChanges called', changes);
}
ngDoCheck(): void {
console.log('ngDoCheck called');
}
ngAfterContentInit(): void {
console.log('ngAfterContentInit called');
}
ngAfterContentChecked(): void {
console.log('ngAfterContentChecked called');
}
ngAfterViewInit(): void {
console.log('ngAfterViewInit called');
}
ngAfterViewChecked(): void {
console.log('ngAfterViewChecked called');
}
ngOnDestroy(): void {
console.log('ngOnDestroy called');
}
}
after applying this directive on html, we got the output
For more practical example is here stackblitz link
Upvotes: 0
Reputation: 7706
Contributing to Ofig's answer, the Directive lifecycle hooks. would be:
Upvotes: 2
Reputation: 754
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
Upvotes: 11