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

时间:2018-05-22 09:58:23

标签: angular5

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

当我在ngOnInit上创建组件时,我收到“无法读取属性'清除'未定义”的错误。

这是我的组件:

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 个答案:

答案 0 :(得分:0)

AngularJS!== Angular,你应该删除标签。也许添加“Typescript”

无论如何,我在这里完成了你正在寻找的事情

Blitz

在Angular4 + Renderer2 中添加了以下内容:

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);
}