繁体   English   中英

Angular 2-具有* ngIf的局部变量/模板引用变量-数组的第一个元素未绑定

[英]Angular 2 - Local Variable/Template Reference Variable with *ngIf - ONLY first element of array not binding

请在此处插入: https ://plnkr.co/edit/te67zdtkVkNCUzEtW5XO ? p = preview参见app.ts

背景:

父组件具有一个数组,并在该数组中显示一个元素。 ChildComponent是一个显示数组的列表,带有单击元素时设置的变量selectedIdx

selectNumber(idx: number) {
    this.selectedIdx = idx;
  }

通过将子级存储为局部变量#child并使用child.selectedIdx对其进行访问,ParentComponent从该子级获取selectedIdx值。

问题:

子组件中的selectedIdx与访问它的父组件之间的绑定对于数组中除第一个元素(索引0)之外的每个元素都非常适用-如果单击1 ,则索引为0的元素Selected Number In Parent: _Selected Number In Parent: _消失了。

这意味着*ngIf为false,意味着selectedIdxnull

但是,情况并非如此,因为当我在子组件的selectNumber()函数中设置断点时, this.selectedIdx设置为0。父级检索值0,然后再思考时,一定有些古怪。它是空的吗?

任何帮助表示赞赏,非常感谢。

基于: https : //angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-local-var

这是因为在Javascript 0 == false ,因此您的*ngIf表达式与0比较时返回false

更改为:

*ngIf="child.selectedIdx !== undefined"

这个答案有一个很好的表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM