I'm fairly new to Angular, so bear with me.
I want to dynamically insert HTML into a page and have it treated as an Angular template containing components/directives/etc.
As a contrived example, say I have my main app component HTML:
<div #pageContent></div>
And I have my app component TS:
import { Component, ElementRef, ViewChild, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
@ViewChild('pageContent') pageContent: ElementRef;
ngOnInit() {
this.pageContent.nativeElement.innerHTML = `
<h1>Test HTML</h1>
<a routerLink="/test">Test</a>
<p>Regular paragraph text</p>
`;
}
}
This is just an example, but in my actual app the HTML will be loaded by a service at run time, not hard-coded as above, so the HTML to be inserted will not be known at compile time.
This example renders a page with plain HTML, and the anchor tag does not function as an Angular RouterLink
component.
I understand that Angular intentionally does not ship with the compiler in order to save on download size, so I can't just say "parse this HTML" and have it do all the leg work for me.
And I understand that there are risks associated with inserting HTML dynamically, but let's assume that I have a good reason to do it anyway and I have other protections in place to prevent malicious HTML from being inserted.
I'm wondering if, for example, I could manually look for any anchor tags in the incoming HTML, manually create a RouterLink
instance and replace it in the rendered HTML in place of the old, non-functioning anchor tag.
I want to be able to do the same with custom components as well, not just RouterLink
.
I'm completely open to suggestion on how to achieve this - the above was just my best guess at how it might work.
The only examples I can find of this kind of thing are for Angular 1.x, but I'm using Angular 8.
Thanks