【问题标题】:Angular: How to dynamically load a component defined by a string?Angular:如何动态加载由字符串定义的组件?
【发布时间】:2020-01-25 00:24:21
【问题描述】:

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

我尝试使用DomSanitizer

this.sanitizer.bypassSecurityTrustHtml(parsedLinksString);

但这并没有正确绑定click 事件处理程序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');
  }

}

【问题讨论】:

  • 您是否将父 DOM 元素上的 innerHTML 属性用于呈现的字符串?来自here
  • 这让我觉得是XY Problem。如果您询问您想要获得什么结果或功能,人们可能会更好地帮助您。尝试通过 HTML 字符串创建这样的按钮的原因是什么?
  • 是的,我尝试使用 innerHtml 属性并呈现它,但是(单击)事件不起作用,因为它是纯 HTML 并且不理解 Angular 绑定。
  • 您将如何开发以下组件?一个通知组件,它连接到一个商店,任何组件都可以调用一个动作并显示通知。但是,这些通知文本可能包含号召性用语链接(例如,单击此处了解更多信息)。此链接是动态内容,还必须绑定到 Angular 类中的方法/事件

标签: angular typescript angular-dynamic-components


【解决方案1】:

Angular 安全模型的设计使得添加到[innerHTML]="myOutput" 的 HTML 不被处理(即不执行脚本并且不触发事件)。

编译 HTML 的 Angular 选项包括:

将 HTML 添加到组件模板

在您的示例中,HTML 将进入 sample-component.component.html。要在模板中动态包含或排除 HTML,请使用 structural directives,例如 *ngIf*ngFor

创建一个动态组件以在运行时加载

Dynamic Component Loader

Stackblitz Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 2021-06-24
    • 2019-10-19
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多