Angular:如何动态加载由字符串定义的组件? [英] Angular: How to dynamically load a component defined by a string?
问题描述
如何编译由字符串定义的组件并将其呈现在模板中?
How do I compile a component defined by a string and render it in my template?
我尝试使用 DomSanitizer
:
I tried using DomSanitizer
:
this.sanitizer.bypassSecurityTrustHtml(parsedLinksString);
但这并不能正确绑定 click
事件处理程序 onButtonClick()
.
But that doesn't properly bind the click
event handler onButtonClick()
.
@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');
}
}
推荐答案
设计Angular安全模型时,不会处理添加到 [innerHTML] ="myOutput"
的HTML(即脚本是未执行且未触发事件.
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).
用于编译HTML的角度选项包括:
Angular options to compile HTML include:
在您的示例中,HTML将放入 sample-component.component.html
中.要在模板中动态包含或排除HTML,请使用结构指令,例如 * ngIf
和 * ngFor
.
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
.
请参见> 动态组件加载器
这篇关于Angular:如何动态加载由字符串定义的组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!