Angular:如何利用*ngFor动态展示指定组件?
核心思路
把Footer类型与对应组件的映射关系抽成数组,通过*ngFor遍历筛选匹配项,再借助Angular的ngComponentOutlet指令动态渲染组件,避免重复写大量*ngIf判断,提升代码扩展性与整洁度。
步骤实现
1. 在父组件类中定义组件映射列表
先导入所有Footer组件,然后创建数组维护类型与组件的对应关系:
import { Component } from '@angular/core'; import { FooterType1Component } from './footer-type1.component'; import { FooterType2Component } from './footer-type2.component'; import { FooterType3Component } from './footer-type3.component'; import { FooterType4Component } from './footer-type4.component'; // 后续新增组件只需在此导入并添加到数组 @Component({ // 组件元数据(如selector、templateUrl等) }) export class YourParentComponent { // 维护Footer类型与组件的映射 footerComponentMap = [ { type: 'Type1', component: FooterType1Component }, { type: 'Type2', component: FooterType2Component }, { type: 'Type3', component: FooterType3Component }, { type: 'Type4', component: FooterType4Component } ]; constructor(public configService: ConfigService) {} }
2. 修改模板代码
用*ngFor遍历映射数组,筛选出与当前配置匹配的项,再用ngComponentOutlet渲染组件:
<div class="footer-wrapper__fm"> <ng-container *ngFor="let item of footerComponentMap" *ngIf="item.type === configService.defaultOptions.ConfigsNew.FooterType" > <ng-container *ngComponentOutlet="item.component"></ng-container> </ng-container> </div>
扩展说明
- 新增组件更便捷:后续添加新的Footer类型时,只需导入组件并在
footerComponentMap数组中新增一条映射,无需修改模板代码。 - 传递数据支持:如果需要给动态组件传参,可以利用
ngComponentOutlet的inputs参数,示例:<ng-container *ngComponentOutlet="item.component; inputs: { footerConfig: configService.defaultOptions.ConfigsNew }"></ng-container> - 版本适配:Angular 9及以后无需手动配置
entryComponents,组件只要在模块中声明(或使用独立组件)即可;Angular 8及之前需要将动态组件加入模块的entryComponents数组。
内容的提问来源于stack exchange,提问作者Hovhannes Gevorgyan
相关产品推荐
相关产品推荐

