You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular:如何利用*ngFor动态展示指定组件?

用*ngFor结合动态组件实现Footer的灵活渲染

核心思路

把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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 13:37:26