如何动态传递角度7

时间:2019-03-06 13:59:46

标签: angular angular7

我有一个空的通用form-dialog-component,我想用它以动态的方式显示另一个特定的表单,而不用静态地放置另一个表单的选择器

这是我的form-dialog.component.ts

import { Component, OnInit} from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';
import { DataEditionMode } from 'src/app/constants/enum';

@Component({
selector: 'app-form-dialog',
templateUrl:  './form-dialog.component.html',
styleUrls: ['./form-dialog.component.css']
})
export class FormDialogComponent implements OnInit {
 dataEditionMode:DataEditionMode
 editedInstance:any
 component:any
 tagName:any

 constructor(@Inject(MAT_DIALOG_DATA) public data: any,
  public matDialogRef: MatDialogRef<FormDialogComponent>) { 
   this.dataEditionMode = data["dataEditionMode"];
   this.editedInstance = data["editedInstance"];
   this.component=data["component"]; //Contain the name of my specific form (DemandeFormComponent OR CommandeFormComponent ...)
 }

 ngOnInit() {
 }

 cancel() {
  this.matDialogRef.close({
   "status": "canceled"
  });
 }
}

这是我的form-dialog.component.html

<div [ngSwitch]="component">
    <app-form-demande   *ngSwitchCase="'DemandeFormComponent'" ></app-form-demande>
    <app-form-commande   *ngSwitchCase="'CommandeFormComponent'" ></app-form-commande>
</div>

我不想使用ngSwitch并编写每种形式的选择器...

有什么想法可以动态地做到吗?

1 个答案:

答案 0 :(得分:1)

我通常为此目的使用专用组件,

export class ComponentHostComponent implements OnInit {

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver,
    private viewContainerRef: ViewContainerRef,
    private changeDetectorRef: ChangeDetectorRef) { }

  ngOnInit() {
  }

  @Input()
  set component(component: any) {
    this.viewContainerRef.clear();
    if (component) {
      const componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
      const componentRef = this.viewContainerRef.createComponent(componentFactory);
    }
  }
}

您可以像这样在模板中应用此组件

<app-component-host [component]="component"></app-component-host>

我创建了一个关于如何执行此操作的最小堆栈闪电:https://stackblitz.com/edit/angular-ogjs95。请注意,必须将用ComponentFactoryResolver创建的组件添加到entryComponents的{​​{1}}数组中。