问题
How do I compile a component defined by a string and render it in my template?
I tried using DomSanitizer:
this.sanitizer.bypassSecurityTrustHtml(parsedLinksString);
But that doesn't properly bind the click
event handler onButtonClick()
.
Desired Functionality
@Component({
selector: 'app-sample-component',
templateUrl: './sample-component.component.html',
styleUrls: ['./sample-component.component.scss']
})
export class SampleComponent {
buildMessage() {
// How do I parse this string and render so that it responds to events?
const myOutput = '<button (click)="onButtonClick()';
}
onButtonClick() {
console.log('Handler for Dynamic Button');
}
}
回答1:
The Angular security model is designed such that HTML added to [innerHTML]="myOutput"
is not processed (i.e. scripts are not executed and events are not triggered).
Angular options to compile HTML include:
Add HTML to a Component Template
In your example, the HTML would go in sample-component.component.html
. To dynamically include or exclude HTML in a template, use structural directives such as *ngIf
and *ngFor
.
Create a Dynamic Component to load at Runtime
See Dynamic Component Loader
Stackblitz Demo
来源:https://stackoverflow.com/questions/58087736/angular-how-to-dynamically-load-a-component-defined-by-a-string