Angular中如何在HTML标签尖括号内使用字符串插值渲染动态组件
Angular 动态遍历渲染组件实现方案
你遇到的问题本质是Angular模板为静态编译机制,无法在运行时动态解析拼接生成的标签名作为组件选择器,要实现遍历配置渲染对应组件的需求,使用官方动态组件加载方案即可,步骤如下:
- 第一步:注册待渲染组件
Angular 13及以上版本使用Ivy编译引擎,无需额外配置;13以下版本需要在所属NgModule的entryComponents数组中注册BoxOneComponent、BoxTwoComponent、BoxThreeComponent三个组件,避免编译时被摇树优化移除。 - 第二步:改造组件配置数组
不要在配置中存储selector字符串,直接引入组件类作为配置项,示例代码:// common-component.ts import { BoxOneComponent } from './box-one/box-one.component'; import { BoxTwoComponent } from './box-two/box-two.component'; import { BoxThreeComponent } from './box-three/box-three.component'; components = [ { componentName: "Box One", comp: BoxOneComponent }, { componentName: "Box Two", comp: BoxTwoComponent }, { componentName: "Box Three", comp: BoxThreeComponent } ] - 第三步:模板中添加动态组件锚点
替换原来错误的动态标签写法,用ng-container作为动态组件的渲染容器:<!-- common-component.html --> <div *ngFor="let com of components"> <ng-container #dynamicCompHost></ng-container> </div> - 第四步:代码中动态创建组件实例
在组件类中获取模板中的锚点容器,遍历配置逐个生成对应组件实例:import { Component, ViewChildren, ViewContainerRef, AfterViewInit, QueryList } from '@angular/core'; // 组件导入、components数组定义省略 export class CommonComponent implements AfterViewInit { @ViewChildren('dynamicCompHost', { read: ViewContainerRef }) compHosts!: QueryList<ViewContainerRef>; ngAfterViewInit(): void { // Angular 14+ 版本可直接调用createComponent传入组件类 this.compHosts.forEach((host, index) => { host.clear(); host.createComponent(this.components[index].comp); }); // Angular 13及以下版本需要先通过ComponentFactoryResolver解析组件工厂 // constructor(private cfr: ComponentFactoryResolver) {} // this.compHosts.forEach((host, index) => { // const factory = this.cfr.resolveComponentFactory(this.components[index].comp); // host.clear(); // host.createComponent(factory); // }) } }
注意:不要尝试通过
[innerHTML]拼接标签字符串的方式渲染组件,Angular会对插入的HTML做安全处理,不会解析其中的自定义组件选择器,无法达到预期渲染效果。
内容的提问来源于stack exchange,提问作者Rupesh Bharuka
相关产品推荐
相关产品推荐

