[英]Angular 2 - Local Variable/Template Reference Variable with *ngIf - ONLY first element of array not binding
Plunker here: https://plnkr.co/edit/te67zdtkVkNCUzEtW5XO?p=preview see app.ts 请在此处插入: https ://plnkr.co/edit/te67zdtkVkNCUzEtW5XO ? p = preview参见app.ts
Background: 背景:
The parent component has an array and displays one element in the array. 父组件具有一个数组,并在该数组中显示一个元素。 The ChildComponent is a list displaying the array, with a variable
selectedIdx
that is set when the element is clicked. ChildComponent是一个显示数组的列表,带有单击元素时设置的变量
selectedIdx
。
selectNumber(idx: number) {
this.selectedIdx = idx;
}
The ParentComponent gets the selectedIdx
value from the child by storing the child as a local variable #child
and accessing it using child.selectedIdx
. 通过将子级存储为局部变量
#child
并使用child.selectedIdx
对其进行访问,ParentComponent从该子级获取selectedIdx
值。
Problem: 问题:
The binding between selectedIdx
in the child component and the parent component accessing it works perfectly for every element in the array apart from the first one (index 0) - if you click 1
, the element at index 0, the Selected Number In Parent: _
disappears. 子组件中的
selectedIdx
与访问它的父组件之间的绑定对于数组中除第一个元素(索引0)之外的每个元素都非常适用-如果单击1
,则索引为0的元素Selected Number In Parent: _
的Selected Number In Parent: _
消失了。
This means the *ngIf
is false which means selectedIdx
is null
. 这意味着
*ngIf
为false,意味着selectedIdx
为null
。
However, this is not the case as when I set a breakpoint in the selectNumber()
function in the child component, this.selectedIdx
is set to 0. There must be something wacky going on with the parent retrieving the value of 0 and then thinking it's null? 但是,情况并非如此,因为当我在子组件的
selectNumber()
函数中设置断点时, this.selectedIdx
设置为0。父级检索值0,然后再思考时,一定有些古怪。它是空的吗?
Any help appreciated, thank you very much. 任何帮助表示赞赏,非常感谢。
Based on: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-local-var 基于: https : //angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-local-var
It's because in Javascript
0 == false
, so your *ngIf
expression returns false
when being compared with 0. 这是因为在
Javascript
0 == false
,因此您的*ngIf
表达式与0比较时返回false
。
Change it to: 更改为:
*ngIf="child.selectedIdx !== undefined"
This answer has an excellent table about this. 这个答案有一个很好的表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.