Angular提供了ComponentFactoryResolver,来协助我们在项目中动态实现Component,而不是把页面需要的所有的组件都写道view里,根据不同的条件来判断显示目标component,当遇到程序现实复杂的需求时非常好用,写出的代码易理解也易维护。今天我们就来看看如何透过ComponentFactoryResolver来动态产生需要的Component。

需求说明

  首先看看以下画面,我们希望点选radio时,可以依照不同的选择切换不同的Component。

  [Anglar]-使用ComponentFactoryResolver动态产生Component

  先不考虑动态产生,只有3个component时,代码可以很简单通过ngIf来判断component是否要被产生,可读性也不至于太差。

 1 <input type="radio" id="showComponentA" name="showComponent" value="componentA" [(ngModel)]="selectedComponentName"/>
 2 <label for="showComponentA">组件 A</label>
 3 
 4 <input type="radio" id="showComponentB" name="showComponent" value="componentB" [(ngModel)]="selectedComponentName"/>
 5 <label for="showComponentB">组件 B</label>
 6 
 7 <input type="radio" id="showComponentC" name="showComponent" value="componentC" [(ngModel)]="selectedComponentName"/>
 8 <label for="showComponentC">组件 C</label>
 9 
10 <app-component-a *ngIf="selectedComponentName === 'componentA'"></app-component-a>
11 <app-component-b *ngIf="selectedComponentName === 'componentB'"></app-component-b>
12 <app-component-c *ngIf="selectedComponentName === 'componentC'"></app-component-c>
View Code

相关文章:

  • 2021-11-15
  • 2021-09-18
  • 2022-12-23
  • 2022-01-05
  • 2022-12-23
  • 2021-04-01
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-25
  • 2022-03-01
  • 2021-10-10
  • 2022-12-23
相关资源
相似解决方案