问题
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?
回答1:
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`,
})
回答2:
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>
来源:https://stackoverflow.com/questions/48556861/angular-4-innerhtml-property-removing-id-attribute