Angular 4 innerHTML属性删除id属性 [英] Angular 4 innerHTML property removing id attribute
问题描述
我正在通过更新元素的innerHTML
加载一些HTML内容(在api调用后加载一些内容).一切正常,只有一件事,那就是从加载的内容中删除id
属性.
组件代码:
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);
}
模板:
<div #div [innerHTML]="content"></div>
在Chrome控制台中进行检查时:
在上面的代码中,this.divContaainer.nativeElement.querySelector('#cafeteria')
返回null
,因为缺少id,当我用calss选择器替换它时,它会起作用.
缺少id
属性,并且存在class属性,是否有任何特定原因?
尝试此 http://plnkr.co/edit/JfG6qGdVEqbWxV6ax3BA?p=preview
使用safeHtml
管道和.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`,
})
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`,
})
这篇关于Angular 4 innerHTML属性删除id属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!