I'm loading some HTML content by updating innerHTML
of an element(loading some content after an api call). Everything works except one thing, which removes id
attribute from the content loaded.
Component code:
content: string;
@ViewChild('div') divContainer: ElementRef;
constructor(private cd: ChangeDetectorRef) {
// actually hee loading content using some api call
setTimeout(() => {
this.content = "<a href='#' id='cafeteria' class='cafeteria'>Cafeteria</a>";
this.cd.detectChanges();
this.divContainer.nativeElement.querySelector('#cafeteria').addEventListener('click', (e) => {
e.preventDefault();
console.log('clicked');
});
}, 1000);
}
Template :
<div #div [innerHTML]="content"></div>
While inspecting in Chrome console :
In the above code this.divContaainer.nativeElement.querySelector('#cafeteria')
returns null
since id is missing and when I replaced with calss selector its working.
The id
attribute is missing and class attribute is there, is there any specific reason for that?
try this http://plnkr.co/edit/JfG6qGdVEqbWxV6ax3BA?p=preview
use a safeHtml
pipe with .sanitized.bypassSecurityTrustHtml
@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value) {
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
@Component({
selector: 'my-app',
template: `<div #div [innerHTML]="content | safeHtml"></div>1`,
})
If you are not using innerHtml at multiple places
In your TS
content = "<a href='#' id='cafeteria' class='cafeteria'>Cafeteria</a>";
newContent:any;
constructor(private sanitized: DomSanitizer) {
this.newContent = this.sanitized.bypassSecurityTrustHtml(content)
}
In your Html
<div #div [innerHTML]="newContent"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With