Plunker here: https://plnkr.co/edit/te67zdtkVkNCUzEtW5XO?p=preview see 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.
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
.
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.
This means the *ngIf
is false which means selectedIdx
is 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?
Any help appreciated, thank you very much.
Based on: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-local-var