角4:动态设置局部变量 [英] Angular 4: setting the local variable # dynamically

查看:86
本文介绍了角4:动态设置局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以动态设置#id(Angular用于构造@ViewChild元素引用的HTML属性)?

Is there a way to dynamically set the #id, the HTML attribute that angular uses to construct the @ViewChild element reference?

特殊需要:我有以下模板,通过* ngFor迭代创建,并且我想在迭代中分配Angular ID.

Specific need: i have the following template, created by iterating through *ngFor, and i wanted to assign the Angular id on the iteration.

<ul>
   <li *ngFor="let link of links">
  </li>
</ul>

在它被解释后,最终得到类似的东西:

And after it gets interpreted, end up with something like:

<ul>
  <li #link1>
   </li>
  <li #link2>
   </li>
 </ul>

现在我知道许多其他获取元素的方法,我可以将#分配给ul元素,以此类推,等等,但是想知道是否有办法在ngFor上做到这一点.

Now I know of many other ways to get the elements, i can assign the # to the ul element, etc, etc, but wondering on whether there is a way to do it on the ngFor.

在查看答案并尝试组合后进行

似乎没有一种方法可以为* ngFor生成的单个元素分配不同的局部变量标识符. 您可以像接受的答案所建议的那样全部获取它们,也可以仅获取父元素,然后从那里找到自己的路.

There doesn't seem to be a way to assign distinct local variable identifiers to the single elements generated by *ngFor. You can either get them all, like the accepted answer suggests, or just get the parent element, and find your way from there.

推荐答案

尽管常规变量和#看起来很相似,但可以将多个元素分配给单个局部模板引用变量:

Despite the seeming resemblance between regular variables and #, multiple elements can be assigned to single local template reference variable:

<ul>
   <li *ngFor="let link of links" #linkRef></li>
</ul>

可以通过以下方式获得

@ViewChildren('linkRef') linkRefs;

这篇关于角4:动态设置局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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