【问题标题】:Angular 4 innerHTML property removing id attributeAngular 4 innerHTML 属性删除 id 属性
【发布时间】:2018-07-11 10:19:59
【问题描述】:

我正在通过更新元素的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 属性存在,有什么具体原因吗?

【问题讨论】:

  • 你能用safeHtml管道和.sanitized.bypassSecurityTrustHtml试试吗
  • @AswinRamesh:让我试试
  • @AswinRamesh :使用DomSanitizer...
  • @AswinRamesh :类似这样的this.content = sanitizer.bypassSecurityTrustHtml("&lt;a href='#' id='cafeteria' class='cafeteria'&gt;Cafeteria&lt;/a&gt;");

标签: javascript angular typescript dom


【解决方案1】:

试试这个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`,
})

【讨论】:

  • 但是我如何确保它仍然可以清理像
【解决方案2】:

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

在您的 TS 中

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

    constructor(private sanitized: DomSanitizer) { 
        this.newContent = this.sanitized.bypassSecurityTrustHtml(content)
    }

在您的 Html 中

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

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 2010-11-16
    • 2021-01-24
    • 2018-05-22
    • 2017-01-30
    • 2017-11-17
    • 2021-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多