Как вызвать угловой компонент во время выполнения? - PullRequest
1 голос
/ 01 июля 2019

Я работаю над приложением angular 7, и у меня есть одно требование:

В моем приложении под углом есть несколько компонентов, таких как componentOne, componentTwo, componentThree и т. Д. В main component (Main) у меня есть массивкак ['componentTwo', 'componentFive'], поэтому я хочу пройти через этот массив и вызвать соответствующий компонент.

Так что, если я хочу вызвать только эти компоненты, я разместлю код следующим образом:

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

Но проблема в том, что я не знаю, какой компонент появится в массиве.Так есть ли способ вызывать компоненты динамически?

Я пробовал это, но это не сработало:

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

Любая помощь заметна, спасибо.

Ответы [ 2 ]

0 голосов
/ 01 июля 2019

Вы можете использовать динамические компоненты. В этом примере 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();
    });
  }
}
0 голосов
/ 01 июля 2019

Возможно, вы можете прослушать вывод из другого компонента и обработать событие в файле typescipt. Пожалуйста, смотрите код ниже. Надеюсь, это поможет.

main.html

<div (updateComponentArray)="updateComponentArray($event)">

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

</div>

main.ts

import { Component} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  componentArray: string[];
  updateComponentArray(components:string[]) {
    this.componentArray = components;
  }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...