【问题标题】:How to get dynamic components created in ngfor component outlet如何获取在 ngfor 组件出口中创建的动态组件
【发布时间】:2021-04-22 07:07:21
【问题描述】:

我有一些代码在 ngfor 循环中从组件类型呈现一组组件

  <div class="outlet">
            <app-customer-personal-details [selectedCustomer]="selectedCustomer"></app-customer-personal-details>
            <ng-template *ngFor="let formComponent of (addedFormComponents$ | async); trackBy: formIdAndOrder"
            [ngComponentOutlet]="formComponent.component">
            </ng-template>
  </div>

上面的formComponent.component 属于Type&lt;GenericFormComponent&gt;

当我运行它时,它会很好地呈现,并且组件会按应有的方式创建。但是,当我尝试获取这些组件的列表以便我可以访问实例时,我一直未定义;

我尝试过的。

最明显的

    // doesnt work returns empty list
    @ViewChildren(GenericFormComponent) formComponents: QueryList<GenericFormComponent>;

然后我也试过了

// Doesnt work returns empty list
@ViewChildren(TemplateRef, {read: GenericFormComponent}) formComponents: QueryList<GenericFormComponent>;

我还尝试使用

为我的组件提供注入令牌
@Component({
    selector: 'app-observation',
    templateUrl: './observation.component.html',
    styleUrls: ['./observation.component.scss'],
    providers: [
        { provide: GenericFormComponent, useExisting: ObservationComponent }
    ]
})
export class ObservationComponent extends GenericFormComponent implements OnInit {

这些方法都不起作用。

是否可以访问使用 ngfor ngComponentOutlet 创建的组件?

注意这是在 Angular 11 上。

【问题讨论】:

    标签: javascript angular angular11


    【解决方案1】:

    我把解决方案放在this repo on stackblitz

    您可以通过将组件动态添加到ViewContainerRef 来实现。然而,我没有运气,使用ngComponentOutlet,我最好的猜测是 Ivy 需要使用“提前类型分析”模板来编译 它需要静态分析你的模板子>

    但是,请注意: 这种技术确实会影响 Ivy,我不太确定,但它可能会导致 AOT/SSR 和生产构建出现问题,所以要小心使用它。

    【讨论】:

    • 感谢您的回答,不幸的是我不能使用这样的答案,因为我想使用 Angulars ngfor trackBy 函数优化来避免在 dom 上重新渲染,因为我的组件的顺序很重要。我之前尝试过这样的方法,但我无法存储组件并实现我想要的,但我失去了 NgFor 优化带来的好处。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2018-06-18
    相关资源
    最近更新 更多