angular动态组件探坑之旅

angular动态组件有两种创建方式,这篇只说一种,用大白话讲,就是先把要用到的各种组件提前写好,然后在需要的地方动态调用。

第一步:先准备若干要用到的组件,直接上图(因为这儿需要传递参数,所以组件中会有input指令)

这儿只是个简单例子,可以理解为component A,既然是动态组件,肯定会有B、C、D。。。。

第二步:编写动态模块容器,

/**
 * Created by NewBee on 2018/7/2.
 */
import {Component,ViewChild, Input, ViewContainerRef, ComponentFactoryResolver,OnInit, OnDestroy, ComponentRef, ChangeDetectorRef} from '@angular/core';
import {CpuComponent} from './cpu/cpu.component';
import {MemComponent} from './mem/mem.component';
import {DY1Component} from './DY1Component';

@Component({
    selector: 'dynamic',
    template: ``
})
export class DynamicCom implements OnInit, OnDestroy{

    @Input() inputs:any;         //加载组件需要传入的参数组

    @Input() component:any;     //需要加载的组件名

    private currentComponent: ComponentRef<any>;
    
    comps: any ;

    constructor(private vcr: ViewContainerRef, private cfr: ComponentFactoryResolver) { }

    ngOnInit() {
        if(this.component == 'cpu'){
            this.comps = CpuComponent;
        }else if(this.component == 'mem'){
            this.comps = MemComponent;
        }else{
            this.comps = DY1Component;
        }
    }

    loadComponent() {

        let com = this.cfr.resolveComponentFactory(this.comps);
        this.vcr.clear();
        let component = this.vcr.createComponent(com);
        if(!this.inputs){
            this.inputs={}
        }else{
            for (let key in this.inputs) {
                component.instance[key] = this.inputs[key];
            }
        }
        this.destroy();
        this.currentComponent = component;
    }

    destroy() {
        if (this.currentComponent) {
            this.currentComponent.destroy();
            this.currentComponent = null;
        }
    }

    ngAfterViewInit() {

        setTimeout(() => this.loadComponent(),0);//settimeout解决开发环境变更检测报错(多检测了一次)

    }

    ngOnDestroy() {
        this.destroy();
    }
}

上述代码如果不是因为传参缘故,真正有用的就两行,即

loadComponent()方法中的:
  let com = this.cfr.resolveComponentFactory(this.comps);
let component = this.vcr.createComponent(com);

传参:

component.instance[key] = this.inputs[key];

第三步:想要使用动态组件,必须先将componentA、B、C、D等声明到这些组件的子根module的entryComponents中,如图:

第四步:调用动态组件容器,显示动态组件;

<dynamic *ngFor="let temp of temps" [component]="temp.item" [inputs]="{'internal':alias,'size':temp.size}"></dynamic>

以上就是所有,当然其中还有很多坑,比如

由于angular的变更检测机制,如果直接调用loadComponent方法,开发环境会莫名其妙的报错,


查了下,说是生产环境下这个错误就不会有了,但是强迫症患者,只能把它解决掉,加上setTimeout完美解决。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个Angular动态组件示例,该组件可以根据输入的组件类型动态创建并显示组件: app.component.ts ``` import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core'; import { DynamicComponent } from './dynamic.component'; @Component({ selector: 'app-root', template: ` <div #container></div> <button (click)="createComponent('dynamic')">Create Dynamic Component</button> `, }) export class AppComponent { @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef; constructor(private resolver: ComponentFactoryResolver) {} createComponent(type: string) { // 根据组件类型获取组件工厂 const factory = this.resolver.resolveComponentFactory(DynamicComponent); // 创建组件实例 const componentRef = this.container.createComponent(factory); // 设置组件属性 componentRef.instance.type = type; } } ``` dynamic.component.ts ``` import { Component, Input } from '@angular/core'; @Component({ selector: 'app-dynamic', template: ` <div *ngIf="type"> Dynamic Component Type: {{ type }} </div> `, }) export class DynamicComponent { @Input() type: string; } ``` 在这个例子中,我们首先在`AppComponent`中使用`ViewChild`获取了一个`ViewContainerRef`引用,这个`ViewContainerRef`表示了一个可以动态添加组件的容器。然后,我们在`createComponent`方法中根据输入的组件类型获取了一个组件工厂,并使用`createComponent`方法创建了一个组件实例,并将其添加到了容器中。最后,我们还在`DynamicComponent`中添加了一个`Input`属性`type`,用于接收传递进来的组件类型。 使用这个动态组件的示例可以参考以下内容: ``` <app-root></app-root> ``` 在页面中添加了一个按钮,当点击按钮时,会调用`AppComponent`中的`createComponent`方法创建一个`DynamicComponent`实例,并将其添加到页面中的容器中。这个`DynamicComponent`实例会根据传递进来的组件类型显示不同的内容。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值