我正在创建一个类似于表单创建器的页面。用户将单击并将不同的组件添加到页面中,这会将条目添加到“组件”变量中,如下所示:
组件 1 的示例:
const childComponent = this.componentFactoryResolver.resolveComponentFactory(Component1);
this.components.push(childComponent);
因此,组件数组将具有 ComponentFactory 元素的集合。
然后我在 HTML 中动态且有条件地创建组件,如下所示:
<div cdkDropList class="example-list" style="margin: 20px" (cdkDropListDropped)="drop($event)">
<div cdkDrag *ngFor="let cmp of components">
<ng-container *ngIf="cmp.componentType.name=='Component1'">
<app-Component1></app-Component1>
</ng-container>
<ng-container *ngIf="cmp.componentType.name=='Component2'">
<app-Component2></app-Component2>
</ng-container>
<ng-container *ngIf="cmp.componentType.name=='Component3'">
<app-Component3></app-Component3>
</ng-container>
</div>
</div>
到目前为止工作正常。现在,当用户单击“保存”按钮时,它应该获得页面上所有组件的列表。我最终需要它,因为组件是可编辑的,所以值会改变。列表“组件”不能使用,因为它只包含工厂元素。
是否可以获取在 HTML 中声明的组件实例?我正在尝试@ViewChildren,但我可能需要为每个组件类型添加它,所以我不会按照用户添加的顺序获取它。
最后,我尝试在代码中创建组件,然后使用 ComponetFactoryResolver 将其添加到页面。然而,它们中的每一个都需要在其中声明指令“cdkDrag”,使用这种方法这是不可能的。
谢谢。
最佳答案
使用循环时,模板引用变量可以引用多个项目。
这显示在 this stackblitz 中正如您所看到的,两个元素都有正确的类实例。
希望这有帮助!
<ng-container *ngFor="let i of [0, 1]; last as isLast; first as isFirst">
<hello *ngIf="isFirst" #child name="{{ name }}"></hello>
<goodbye *ngIf="isLast" #child name="{{ name }}"></goodbye>
</ng-container>
<p>
Start editing to see some magic happen :)
</p>
import { Component, ViewChildren, QueryList } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
@ViewChildren('child') children: QueryList<any>;
ngOnInit() {
setTimeout(() => console.log(this.children.first), 1000);
setTimeout(() => console.log(this.children.last), 1000);
}
}
日志
HelloComponent
name: "Angular"
__proto__: Object
GoodbyeComponent
name: "Angular"
__proto__: Object
关于Angular 7 - 获取 HTML 中声明的所有组件的组件实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56129815/