Angular通过ComponentFactoryResolver动态管理组件

        在 Angular 中,通过 ViewContainerRef ComponentFactoryResolver 来创建和管理动态组件。

一、获取容器元素的ViewContainerRef 对象,通过ComponentFactoryResolver 创建组件

【1】html

 

//容器组件

【2】ts

import { OnInit, Component, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import {ChildrenComponent} from '../children/children.component';
@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
    //获取ViewContainerRef组件
  @ViewChild('container', { static: true, read: ViewContainerRef }) container: ViewContainerRef;
  constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
  index = 0;
  ngOnInit() {}
  createComponent() {
    // 获取组件工厂
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildrenComponent);
    // 创建组件实例
    const componentRef = this.container.createComponent(componentFactory);
    // 设置组件属性
    componentRef.instance.index = ++this.index;
    // 订阅组件事件
    componentRef.instance.myOutput.subscribe((event) => {
      console.log('Received data:', event);
    });
  }
  removeComponent() {
    // 移除组件
    this.container.remove();
  }
}

二、动态组件

【1】html

我是动态组件 {{index}},点我发送消息

【2】ts

import { Component, Input, OnInit,Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-children',
  templateUrl: './children.component.html',
  styleUrls: ['./children.component.css']
})
export class ChildrenComponent implements OnInit {
  @Input() index: number = 0;
  @Output() myOutput: EventEmitter =new EventEmitter(); 
  constructor() { }

  ngOnInit() {
  }
  sendMessage() {
    this.myOutput.emit(`我是第${this.index}个组件`)
  }
}

三、效果

1、点击“创建组件”,依次动态创建组件

Angular通过ComponentFactoryResolver动态管理组件_第1张图片

 2、点击创建的组件,发送消息

Angular通过ComponentFactoryResolver动态管理组件_第2张图片

你可能感兴趣的:(Angular,angular.js,前端,javascript,angular动态创建组件)