代码之家  ›  专栏  ›  技术社区  ›  Juan

如何在ngOnInit()上动态创建组件?

  •  0
  • Juan  · 技术社区  · 6 年前

    如何在ngOnInit()上动态创建组件?

    当我在ngOnInit上创建组件时,出现了一个错误“Cannot read property'clear'of undefined”。

    这是我的组件:

    import { Component, OnInit, ViewChild, ViewContainerRef, ComponentFactoryResolver, ComponentRef, ComponentFactory } from '@angular/core';
    import { SpinnerService } from '../../tools/spinner/spinner.service';
    import { CardService } from './card.service';
    import { CardDatagridComponent } from './card-datagrid/card-datagrid.component';
    
    @Component({
      selector: 'app-card',
      templateUrl: './card.component.html',
      styleUrls: ['./card.component.scss']
    })
    export class CardComponent implements OnInit {
      @ViewChild("cardDataGridContainer", { read: ViewContainerRef }) container;
      public renderReady: boolean = false;
      public componentRef: ComponentRef<any>;
      public selectedStatus = 'A';
    
      constructor(private spinner: SpinnerService, private cardService: CardService, private resolver: ComponentFactoryResolver) { }
    
      ngOnInit() {
        this.spinner.show();
        setTimeout(() => {
          this.spinner.hide();
          this.renderReady = true;
        }, 2000);
        this.selectTabStatus(this.selectedStatus);
      }
    
      selectTabStatus(status) {
        this.selectedStatus = status;
        this.createComponent(status);
      }
    
      createComponent(status) {
        this.container.clear();
        const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(CardDatagridComponent)
        this.componentRef = this.container.createComponent(factory);
        this.componentRef.instance.cardStatus = status;
      }
    
      ngOnDestroy() {
        this.componentRef.destroy(); 
      }
    }
    

    有什么建议吗?谢谢!

    1 回复  |  直到 6 年前
        1
  •  0
  •   Sampgun    6 年前

    安格拉瑞斯!==角度,你应该去掉标签。也许加上“Typescript”

    不管怎样,在这里我完成了你想要的

    Blitz

    角度4+ 渲染器2 添加如下:

    import {Renderer2, ElementRef} from "@angular/core";
    
    constructor(private targetEl: ElementRef, private renderer: Renderer2) {
    
        this.$matCard = this.renderer.createElement('mat-card');
    
        const matCardInner = this.renderer.createText('Dynamic card!');
        this.renderer.appendChild(this.$matCard, matCardInner);
        const container = this.targetEl.nativeElement;
        this.renderer.appendChild(container, this.$matCard);
    }