Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 innerHTML property removing id attribute

I'm loading some HTML content by updating innerHTML of an element(loading some content after an api call). Everything works except one thing, which removes id attribute from the content loaded.

Component code:

 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);
  }

Template :

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

While inspecting in Chrome console :

enter image description here

In the above code this.divContaainer.nativeElement.querySelector('#cafeteria') returns null since id is missing and when I replaced with calss selector its working.

The id attribute is missing and class attribute is there, is there any specific reason for that?

like image 235
Pranav C Balan Avatar asked Feb 01 '18 06:02

Pranav C Balan


2 Answers

try this http://plnkr.co/edit/JfG6qGdVEqbWxV6ax3BA?p=preview

use a safeHtml pipe with .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`,
})
like image 181
Aswin Ramesh Avatar answered Oct 20 '22 02:10

Aswin Ramesh


If you are not using innerHtml at multiple places

In your TS

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

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

In your Html

<div #div [innerHTML]="newContent"></div>
like image 9
Prashant Avatar answered Oct 20 '22 03:10

Prashant