Angular 4 innerHTML属性删除id属性

Pra*_*lan 7 javascript dom typescript angular

我通过更新innerHTML元素(在api调用后加载一些内容)来加载一些HTML内容.一切都有效,除了一件事,它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);
  }
Run Code Online (Sandbox Code Playgroud)

模板:

 <div #div [innerHTML]="content"></div>
Run Code Online (Sandbox Code Playgroud)

在Chrome控制台中进行检查时:

在此输入图像描述

在上面的代码this.divContaainer.nativeElement.querySelector('#cafeteria')返回,null因为id丢失,当我用calss选择器替换它的工作.

id属性缺失且类属性存在,是否有任何具体原因?

小智 9

试试这个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`,
})
Run Code Online (Sandbox Code Playgroud)


小智 7

如果您没有在多个地方使用 innerHtml

在你的 TS

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

    constructor(private sanitized: DomSanitizer) { 
        this.newContent = this.sanitized.bypassSecurityTrustHtml(content)
    }
Run Code Online (Sandbox Code Playgroud)

在你的 HTML

<div #div [innerHTML]="newContent"></div>
Run Code Online (Sandbox Code Playgroud)