typescript ngFor 中动态元素的 angular viewChild

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51252429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:31:33  来源:igfitidea点击:

angular viewChild for dynamic elements inside ngFor

angulartypescriptngfor

提问by Gustavo Berwanger

My template has something like this:

我的模板有这样的东西:

<div *ngFor="let data of array">
    <div #div></div>
</div>

is there a way for me to name each div differently using the #? And if so, how can I access them later in my TS file?

有没有办法让我使用# 以不同的方式命名每个 div?如果是这样,我以后如何在我的 TS 文件中访问它们?

by the way, what are these # called? I cant search for them since I have now idea what these are (I just know what they're used for)

顺便问一下,这些#叫什么名字?我无法搜索它们,因为我现在知道这些是什么(我只知道它们的用途)

回答by Batajus

As @Commerical Suicide mentioned you cannot set the references dynamically.

正如@Commerical Suicide 提到的,您不能动态设置引用。

The #divis called template reference variable.

#div被称为模板引用变量

You can access your divsvia ViewChildrenin you *.tsfile.

您可以访问您的div通过ViewChildren在你*.ts的文件。

Sample: @ViewChildren('div') divs: QueryList<ElementRef>

样本: @ViewChildren('div') divs: QueryList<ElementRef>

Then you can call multiple methods on your new QueryList, like forEachor find.

然后你可以在你的 new 上调用多个方法QueryList,比如forEachfind