angular动态组件容器(直接传入组件名称,自动生成组件)

前言:在工作中遇到需要二次封装的组件,需求是组件不是固定的,需要根据情况来显示组件。
那么怎么做呢。
网上查了angular的资料发现了ComponentFactoryResolver这个服务,他可以将我们的类直接转为组件。
这里还需要用到模板来充当加载这个组件的容器

//htm代码
<ng-template #container></ng-template>

ts

import { Component, ComponentFactoryResolver, Input, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
/**
 * 动态组件容器,直接传入组件
 */
@Component({
  selector: 'div[gas-container]',
  templateUrl: './gas-container.component.html',

  styleUrls: ['./gas-container.component.scss']
})
export class GasContainerComponent implements OnInit {

  constructor(protected resolver: ComponentFactoryResolver,) { }
  public _component: any;//组件
  public template: any;//已经生成的组件

  @Input()
  public set component(value: any) {
    this._component = value;
    //检测到组件变化自动生成新组件
    this.initCompontent(value);
  }
  public _data: any;//组件数据
  @Input()
  public set data(value: any) {
    this._data = value;//监听传入组件的数据
    this.template && (this.template.instance.data = value);//将数据直接初始化入生成后的组件
  }
  @ViewChild("container", { read: ViewContainerRef }) container: ViewContainerRef;
  /**
   * 在指定位置生成组件,注此类组件全是动态组件,需要在module中entryComponents引入
   * @param com 组件实例化对象
   */
  initCompontent(com) {
    this.container.clear();
    let component = this.resolver.resolveComponentFactory(com);
    this.template = this.container.createComponent(component);

  }

  ngOnInit() {

  }

}

用法

   <div gas-container [component]="组件名称" [data]="组件数据"> </div>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值