1

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

Helen
  • 727
  • 8
  • 13
  • Can you share a reduced and minimal code sample of the problem? – shusson Feb 16 '17 at 00:17
  • Hi shusson, I've made the array a simple array of numbers if that simplifies the problem: https://plnkr.co/edit/te67zdtkVkNCUzEtW5XO?p=preview – Helen Feb 16 '17 at 00:23
  • It looks like you got some good answers, but what I originally meant was actually show the minimal template and component in the question. – shusson Feb 16 '17 at 00:28

1 Answers1

3

It's because in Javascript 0 == false, so your *ngIf expression returns false when being compared with 0.

Change it to:

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

This answer has an excellent table about this.

developer033
  • 24,267
  • 8
  • 82
  • 108