How can I store HTML with component directives in my database and use it as part of a component template in Angular?
For example, if I have:
<div [innerHTML]="injectMe"></div>
in the App component template and this code in the app component:
export class AppComponent {
injectMe = "<p>Paragraph</p> <app-injected></app-injected> ";
}
then create a component named injected:
template:
<p> injected works! </p>
code:
@Component({
selector: 'app-injected',
templateUrl: './injected.component.html',
styleUrls: ['./injected.component.css']
})
export class InjectedComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
When trying to display the dynamically generated HTML, a warning "sanitizing HTML stripped some content" appears. In an attempt to resolve this, I added a call to mark the string as safe using: this.sanitizer.bypassSecurityTrustHtml
export class AppComponent {
injectHtml = "<p>Paragraph</p> <app-injected></app-injected> ";
injectMe: any;
constructor(private sanitizer: DomSanitizer){
this.injectMe = this.sanitizer.bypassSecurityTrustHtml(this.injectHtml);
}
}
After making this change, the directive tag remained in the HTML without any console warnings about sanitization, but the component did not seem to be processed by Angular. Research led me to consider using a component factory to create components dynamically, however, manual parsing of the HTML may be required to detect components.