Angular组件的高级玩法

如果想要手动创建组件,需要在app.module.ts里面加一个配置项,例如需要手动创建ChildOneComponent实例,添加到entryComponents告诉脱机模板编译器编译它们并为它们创建工厂

entryComponents:[ChildOneComponent]

离线模板编译器(OTC)只生成实际使用的组件。如果组件不直接用于模板,OTC不知道是否需要编译。有了entryComponents,你可以告诉OTC也编译这些组件,以便在运行时可用

构造函数里面需要注入组件工厂解析器ComponentFactoryResolver

constructor(private resolver: ComponentFactoryResolver) { }
./test-dynamic-component/test-dynamic-component.component.ts

import { Component, OnInit, ViewChild, ViewContainerRef, ComponentFactoryResolver, ComponentRef } from '@angular/core';
import { ChildOneComponent } from './child-one/child-one.component';

@Component({
  selector: 'test-dynamic-component',
  templateUrl: './test-dynamic-component.component.html',
  styleUrls: ['./test-dynamic-component.component.scss']
})
export class TestDynamicComponentComponent implements OnInit {
  @ViewChild('dyncontainer', { read: ViewContainerRef })
  dyncontainer: ViewContainerRef

  comp1: ComponentRef<ChildOneComponent>;

  constructor(private resolver: ComponentFactoryResolver) { }

  ngOnInit() {
  }

  ngAfterContentInit() {
    console.log('动态的创建组件的实例...');
    //定义变量拿到解析的子组件
    const childComp = this.resolver.resolveComponentFactory(ChildOneComponent);
    //在标识的容器内创建解析好的子组件,拿到这个DOM节点
    this.comp1 = this.dyncontainer.createComponent(childComp);
    //通过DOM节点的实例,可以设置属性
    this.comp1.instance.title = '父组件动态赋值的标题';
    //订阅子组件发送过来的事件
    this.comp1.instance.myEvent.subscribe((data) => {
      console.log(data);
    });

    // let comp2 = this.dyncontainer.createComponent(childComp);
    // comp2.instance.title = '我是第2个动态组件';
    // let comp3 = this.dyncontainer.createComponent(childComp);
    // comp3.instance.title = '我是第3个动态组件';
    // let comp4 = this.dyncontainer.createComponent(childComp, 0);
    // comp4.instance.title = '我是第4个动态组件';
  }

  public delComp():void{
    this.comp1.destroy();
  }

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容