Angular:如何动态加载由字符串定义的组件? [英] Angular: How to dynamically load a component defined by a string?

查看:83
本文介绍了Angular:如何动态加载由字符串定义的组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编译由字符串定义的组件并将其呈现在模板中?

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.

请参见> 动态组件加载器

Stackblitz演示

这篇关于Angular:如何动态加载由字符串定义的组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆