我正在开发实现 Angular Web 组件概念的项目 Angular 指南
现在我们只有 2 或 3 个元素将根据用户的输入动态显示。 用户完成表单后,将下载特定元素的 main.js 文件,并将其显示在模板中的位置。这样,一切就都好了。
示例代码将让您在这里看到问题:
<div *ngIf="isDisplay">
<element-a *ngIf="inpt='a'" [inputForm]="inputForm">
<element-b *ngIf="inpt='b'" [inputForm]="inputForm">
<element-c *ngIf="inpt='c'" [inputForm]="inputForm">
...
<div>
问题是,将来我们将拥有大约 30 个元素,每次有新元素时都重建父应用程序并不是一个好主意。
所以,我想知道是否有任何方法可以执行类似的操作,读取配置文件中的列表并执行类似的操作。
<div *ngFor="let elementName of elementList">
<element-{{elementName}} *ngIf="inpt='elementName'" [inputForm]="inputForm">
<div>
是的,有一种方法可以渲染动态 Angular 自定义元素,而无需每次拥有新元素时都重建父应用程序。您可以使用
ViewContainerRef
类来执行此操作。
import { Component, OnInit, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private viewContainerRef: ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver) { }
ngOnInit() {
// Get the list of element names from the configuration file.
const elementList = ['element-a', 'element-b', 'element-c'];
// Iterate over the list of element names and create a new instance of the corresponding dynamic element for each element name.
for (const elementName of elementList) {
// Get the component factory for the dynamic element.
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(DynamicElementComponent);
// Create a new instance of the dynamic element.
const dynamicElementComponent = this.viewContainerRef.createComponent(componentFactory);
// Set the input property of the dynamic element.
dynamicElementComponent.instance.inputForm = this.inputForm;
// Insert the dynamic element into the DOM.
this.viewContainerRef.insert(dynamicElementComponent.hostView);
}
}
}