Angular 7 - 获取在 HTML 中声明的所有组件的组件实例

Angular 7 - Get component instance of all components declared in HTML

我正在创建一个类似于表单创建器的页面。用户将单击并将不同的组件添加到页面中,这会将条目添加到 "component" 变量中,如下所示:

组件 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>

到目前为止工作正常。现在,当用户单击保存按钮时,它应该会获得页面上所有组件的列表。我最终需要它,因为组件是可编辑的,所以值会改变。列表 "components" 不能使用,因为它只包含 Factory 元素。

是否可以获取在HTML中声明的组件实例?我正在尝试@ViewChildren,但我可能需要为每种组件类型添加它,所以我不会按照用户添加的顺序获取它。

最后,我尝试在代码中创建组件,然后使用 ComponetFactoryResolver 将其添加到页面。但是,它们中的每一个都需要在其中声明指令 "cdkDrag",使用该方法就不可能了。

谢谢。

使用循环时,模板引用变量可以引用多个项目。

这显示在 this stackblitz 中,如您所见,两个元素都有正确的 class 实例。

希望这对您有所帮助!

<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