如何创建对动态创建的组件的引用? [英] How to create reference to a dynamically created component?

查看:46
本文介绍了如何创建对动态创建的组件的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在任何地方都找不到如何创建对从数组动态创建的组件的引用?

I can't find anywhere how to create reference to a component that I create dynamically from array?

HTML

<div *ngFor="let item of items">
    <my-component [data]="item.data"></my-component>
</div>

我需要访问TypeScript代码中的每个< my-component> (将从数组动态创建)

I need to have access to every <my-component> (which will be created dynamically from the array) in the TypeScript code

示例:

items 数组的 length 为2.因此,在TypeScript代码中,我需要具有类似的内容.

The length of items array is 2. So then in TypeScript code I need to have something like this.

myComponent0-对1.的引用.< my-component>

myComponent0 - reference to the 1. <my-component>

myComponent1-引用2.< my-component>

myComponent1 - reference to the 2. <my-component>

谢谢

推荐答案

使用 ViewChildren

import { ViewChildren, QueryList, ... } from '@angular/core';

export class AppComponent {

  @ViewChildren(MyComponent) components: QueryList<MyComponent>

  ...

  ngAfterViewInit() {
    this.components.forEach(componentInstance => console.log(componentInstance));
  }

  ...

}

此处 MyComponent 是组件类的导出名称.通常,它的类型为 QueryList ,因此您基本上可以将其视为数组并做有需要的事情.

Here MyComponent is the exported name of the Component Class. This is generally of type QueryList so you can essentially treat it as an array and do the needful.

仅在组件的 AfterViewInit 挂钩之后可用.

This will only be available after the AfterViewInit hook of the Component.

这是一个 示例StackBlitz 供您参考.

Here's a Sample StackBlitz for your ref.

这篇关于如何创建对动态创建的组件的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆