After making an API call to load HTML content into an element by updating the innerHTML
, everything seems to be working fine except for one issue - the id
attribute gets removed from the loaded content.
Here is the component code:
content: string;
@ViewChild('div') divContainer: ElementRef;
constructor(private cd: ChangeDetectorRef) {
// loading content using an 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>
Upon inspecting in the Chrome console:
https://i.sstatic.net/c8x8l.png
In the code snippet above,
this.divContaainer.nativeElement.querySelector('#cafeteria')
returns null
because the id is missing. However, when I replaced it with a class selector, it worked properly.
The loaded content lacks the id
attribute but retains the class attribute. Is there a specific reason for this behavior?