angular 动态组件 ComponentFactoryResolver

当组件数量不多的话可以利用ngif来判断component
组件目录结构
目录结构
模板代码

<nz-radio-group [(ngModel)]="radioValue" (ngModelChange)="radioValueChange()">
  <label nz-radio nzValue="A">A</label>
  <label nz-radio nzValue="B">B</label>
  <label nz-radio nzValue="C">C</label>
</nz-radio-group>

<ng-container *ngIf="radioValue === 'A'">
  <app-component-a></app-component-a>
</ng-container>
<ng-container *ngIf="radioValue === 'B'">
  <app-component-b></app-component-b>
</ng-container>
<ng-container *ngIf="radioValue === 'C'">
  <app-component-c></app-component-c>
</ng-container>

效果
在这里插入图片描述

但是当选项很多的时候,或者选项通过后端决定等复杂情况下,再用ngif来实现会很麻烦,代码会很容易变得杂乱且不容易维护,这时候就需要动态组件,动态的方式来生成component

1.首先我们先建立一个directive,并注入ViewContainerRef,ViewContainerRef可以让我们知道目前所在的HTML元素包含的view内容,也可以通过它来改变view的结果(例如:动态的产生component,或者动态的移除component等等)。
  执行命令: ng generate directive DynamicComponent
在这里插入图片描述

import {Directive, ViewContainerRef} from '@angular/core';

@Directive({
  selector: '[appDynamicComponent]'
})
export class DynamicComponentDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

2.需要套用这个指令到需要动态产生component的容器上,可以使用ng-template,代码被修改为
注意此时给radio加了一个valueChange事件

<nz-radio-group [(ngModel)]="radioValue" (ngModelChange)="radioValueChange()">
  <label nz-radio nzValue="A">A</label>
  <label nz-radio nzValue="B">B</label>
  <label nz-radio nzValue="C">C</label>
</nz-radio-group>

<ng-template appDynamicComponent></ng-template>

3.注入ComponentFactoryResolver,动态产生component

 /*利用viewChild获取模板元素*/
  @ViewChild(DynamicComponentDirective) componentHost: DynamicComponentDirective | undefined;
  radioValue: string = '';

  /*所有的组件列表*/
  componentList = {
    componentA: ComponentAComponent,
    componentB: ComponentBComponent,
    componentC: ComponentCComponent,
  }


  constructor(public componentFactoryResolver: ComponentFactoryResolver) {
  }

  ngOnInit(): void {
  }

  radioValueChange() {
    /** 利用组件工厂动态生成组件*/
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(
      this.getComponent(this.radioValue)
    );
    /** 获取到模板元素,因为用viewChild获取dom时定义的undefined 所以需要手动as定义一下类型*/
    const viewContainerRef = (this.componentHost as DynamicComponentDirective).viewContainerRef;
    /*将模板上的元素清空*/
    viewContainerRef.clear();
    /*创建组件*/
    viewContainerRef.createComponent(componentFactory);
  }

  getComponent(radioValue: string): any {
    if (radioValue === 'componentA') {
      return this.componentList['componentA']
    } else if (radioValue === 'componentB') {
      return this.componentList['componentB']
    } else {
      return this.componentList['componentC']
    }
  }

写在最后,很多博客中写道最后要引入entryComponents,在新版本中已经被弃用了,不需要再引入了

ng最新版本动态组件写法

@Component({
    selector: 'a-component',
    template: `
        <ng-template #dynamicFilterConditionComponent></ng-template>
    `
})
export class Acomponent implements OnInit {
	// static true表示可以在 完全初始化组件视图之前调用
	// read: ViewContainerRef 表明类型
    @ViewChild('dynamicComponent', { static: true, read: ViewContainerRef }) dynamicComponent: ViewContainerRef;

    componentRef: ComponentRef<any>;
    
	key:string;

	//组件map
    componentsMap = {
        [ConfigTypeKeyEnum.SEARCH_SCOPE]: SearchScopeComponent
    };

    constructor() {}

    ngOnInit(): void {
        this.createComponent();
    }

    createComponent() {
        this.clearComponent();
        this.componentRef = this.filterComponent.createComponent(this.componentsMap[this.type]);
        // 动态组件传值
        this.componentRef.instance.key = this.key;
        this.componentRef.instance.valueChange.subscribe((query) => {
            // 这里用来处理动态创建组件的回调
        });
    }

    clearComponent() {
        this.filterComponent.clear();
    }
}

现在有一个同样能实现动态组件的写法 ,需要ng16的版本

   <ng-container *ngComponentOutlet="item.component; inputs: { headerTitle: item.name }"></ng-container>
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值