Javascript Angular 4 innerHTML属性删除id属性

Javascript Angular 4 innerHTML属性删除id属性,javascript,angular,typescript,dom,Javascript,Angular,Typescript,Dom,我通过更新元素的innerHTML来加载一些HTML内容(在api调用后加载一些内容)。除了从加载的内容中删除id属性的一件事之外,其他一切都可以正常工作 组件代码: content: string; @ViewChild('div') divContainer: ElementRef; constructor(private cd: ChangeDetectorRef) { // actually hee loading content using some api call

我通过更新元素的
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);
  }
内容:字符串;
@ViewChild('div')divContainer:ElementRef;
构造函数(专用cd:ChangeDetectorRef){
//实际上,hee使用一些api调用加载内容
设置超时(()=>{
此参数为:content=“”;
this.cd.detectChanges();
this.divContainer.nativeElement.querySelector(“#caffeeta”).addEventListener('click',(e)=>{
e、 预防默认值();
console.log('clicked');
});
}, 1000);
}
模板:

 <div #div [innerHTML]="content"></div>

在Chrome控制台中检查时:

在上面的代码中,
this.divContaainer.nativeElement.querySelector(“#caffeeta”)
返回
null
,因为缺少id,当我用calss选择器替换它时,它会工作

id
属性缺失,class属性存在,有什么具体原因吗?

试试这个

安全HTML
管道与
消毒过的.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`,
})
@Pipe({name:'safeHtml'})
导出类SafeHtmlPipe实现PipeTransform{
构造函数(私有消毒:domsanizizer){}
转换(值){
返回此.sanitized.bypassSecurityTrustHtml(值);
}
}
@组成部分({
选择器:“我的应用程序”,
模板:`1`,
})

如果您没有在多个位置使用innerHtml

在您的TS中

content = "<a href='#' id='cafeteria' class='cafeteria'>Cafeteria</a>";
newContent:any;

    constructor(private sanitized: DomSanitizer) { 
        this.newContent = this.sanitized.bypassSecurityTrustHtml(content)
    }
content=”“;
新内容:任何;
构造函数(私有已消毒:DomSanitizer){
this.newContent=this.sanitized.bypassSecurityTrustHtml(内容)
}
在您的Html中

<div #div [innerHTML]="newContent"></div>


你能用
安全HTML
管道和
.sanitized.bypassSecurityTrustHtml
@AswinRamesh:让我试试吗try@AswinRamesh:在使用
DomSanitizer
…@AswinRamesh:this
this.content=sanitizer.bypassSecurityTrustHtml(“”)之后,它就工作了