Search code examples
javascripthtmlangulartypescriptinnerhtml

id Attribute of innerHTML value disappears


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.


Solution

  • 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