首页 > 解决方案 > 如何在运行时调用角度组件?

问题描述

我正在研究 Angular 7 应用程序,我有一个要求:

在我的角度应用程序中,我有许多组件,如 componentOne、componentTwo、componentThree 等。在主组件(Main)中,我有一个像 ['componentTwo'、'componentFive'] 这样的数组,所以我想循环遍历这个数组并调用相应的零件。

因此,如果我只想调用这些组件,那么我将这样放置代码:

<div>
   <componentTwo></componentTwo>
   <componentFive></componentFive>
</div>

但问题是我不知道数组中会出现哪个组件。那么有没有办法动态调用组件呢?

我试过了,但没有用:

<div>
   <ng-container *ngFor="let componentName of componentArray">
      <{{componentName}}></{{componentName}}>
   </ng-container>
</div>

任何形式的帮助都是可观的,谢谢。

标签: javascriptangularangular6angular7

解决方案


您可以使用动态补偿。在本例中,ErrorDialogComponent 是在 showErrorAlert 函数中动态创建的。注意 createComponent 和 ComponentFactoryResolver 的使用。您还可以使用其实例设置动态组件的数据。

import { Component, OnInit, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { first } from 'rxjs/operators';

import { ProductsService } from './products.service';
import { ErrorDialogComponent } from '@app/shared/error-dialog/error-dialog.component';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.scss']
})
export class ProductsComponent implements OnInit {

  @ViewChild('errorPlaceHolder', { read: ViewContainerRef, static: false }) errorPlaceHolder: ViewContainerRef;

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver
  ) { }

  async ngOnInit() {
  }

  private showErrorAlert(errorMessage: string) {
    this.showError = true;
    const errorComponentFactory = this.componentFactoryResolver.resolveComponentFactory(ErrorDialogComponent);
    this.errorPlaceHolder.clear();
    const errorCompnent = this.errorPlaceHolder.createComponent(errorComponentFactory);
    errorCompnent.instance.errorMessage = errorMessage;
    errorCompnent.instance.dismiss.subscribe(() => {
      this.errorPlaceHolder.clear();
    });
  }
}

推荐阅读