Issue
I have a directive getting html from a REST endpoint and binding it to a div element via [innerHTML]. After this html is rendered I want to call a function which is globally available to mess with this content.
So what I tried was to create a directive which implements AfterView init and added it to my div element:
<div specialContent [innerHtml]="entry.body">
@Directive({
selector: '[specialContent]'
})
export class SpecialContentDirective implements AfterViewInit {
constructor(
private el: ElementRef
) {}
ngAfterViewInit(): void {
globalObject.applyTo(
this.el.nativeElement.querySelectorAll('.target')
);
}
}
This kind of works but only if the current component which renders the context is freshly loaded. After reloading the content without unloading the component ngAfterViewInit obviously isn't triggered again.
So what's the correct way to do such thing in Angular?
Solution
It is not so clear what you try to achieve with applyTo method.
Why not try to use the directive with an Input ?
in HTML
<div [specialContent]="entry.body">
in directive
@Directive({
selector: '[specialContent]'
})
export class SpecialContentDirective implements OnChanges {
@Input('specialContent') myContent: string;
constructor(
private el: ElementRef
) {}
ngOnChanges(changes: SimpleChanges){
if(changes.myContent) {
this.el.nativeElement.innerHTML = myContent;
globalObject.applyTo(
this.el.nativeElement.querySelectorAll('.target')
);
}
}
}
Answered By - noririco
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.