javascript - 如何在运行时调用角度组件?
问题描述
我正在研究 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>
任何形式的帮助都是可观的,谢谢。
解决方案
您可以使用动态补偿。在本例中,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();
});
}
}
推荐阅读
- html - 如何强制文本超出表格单元格而不改变其大小
- azure - 如何使用 PowerShell 从 Azure 表存储中获取前 X 行?
- php - PHP 从 0/0/0 00:00:00 计算日期间隔
- javascript - 为什么以下 3 行代码返回 1?
- python - 如何正确加载 GeoJson 文件?
- c# - 命名管道 IPC:Python 服务器、C# 客户端
- swift - 如何在 SwiftUI 中圆角并减小列表的大小?
- c# - 有什么方法可以检查 XAML 中的条件
- python - 更新/合并具有不同列名的 2 个数据文件
- octave - Octave如何限制箱线图宽度