Home > Mobile >  id Attribute of innerHTML value disappears
id Attribute of innerHTML value disappears

Time:05-05

I am trying to set the content of a DOM-Element with innerHTML, but it doesn't work as I expect it. The content which I want to set is an a Tag with id and href as attributes, however the id attribute isn't there on the rendered content.

Example Code:

import { Component } from '@angular/core';
@Component({
    selector: 'app-root',
    template: `<div [innerHTML]="html"></div>`,
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'Angular';
    html = '<a href="/" id="foo">link</a>';
}

Any help is welcome.

CodePudding user response:

You should use bypassSecurityTrustHtml method to tell angular that this html is safe to use.

      html = this.sanitizer.bypassSecurityTrustHtml('<a href="/" id="foo">link</a>');
      constructor(private sanitizer: DomSanitizer){}

Working Stackblitz

  • Related