Reputation: 626
Say we have component A as the parent component and component B as the child component. The child has an input what_is_x
that is supplied by the parent. Something like this:
For the parent:
@Component({
selector: 'cmp-A',
directives: [ComponentB],
template: `<cmp-B [what-is-x]="x"></cmp-B>`
})
export ComponentA {
public x: any = [1, 2, 3];
constructor() {
setTimeout(() => this.x.push(10), 2000);
}
}
For the child:
// component B with input what_is_x
@Component({
selector: 'cmp-B',
template: `{{what_is_x}}`
})
export ComponentB {
@Input('what-is-x') public what_is_x: any;
}
My question is, if the parent changed x
by some means, does the child get updated with the new value? According to the "Component communication" chapter in the developer guide (not released yet); it should! but it's not updated for me, tried all betas up till now (0,1,2)
Upvotes: 4
Views: 4471
Reputation: 364677
Update: As of beta.16, {{what_is_x}}
will now update in the view, even if the array reference hasn't changed. See also {{myArray}} now updates in the view as of beta.16.
Original answer:
The default change detection algorithm looks for differences by comparing bound-property values by reference across change detection runs. -- doCheck() API doc
So as @Eric mentioned in a comment, the reason you are not seeing any updates in your view is because you are only binding to the array in your template – {{what_is_x}}
– and since the array reference does not change when we modify the array (e.g., using push()
), change detection does not detect any changes.
If this is really your use case, do as @Eric suggests and return a different array, then change detection will notice that the array reference has changed.
Normally, our templates bind to individual items of the array. E.g.,
<div *ngFor="#item of what_is_x">{{item}}</div>
Since there is a binding created for each item of the array, if we add or remove or modify an item, change detection will notice (and we do not need to return a different array).
For debugging, if you instead use {{what_is_x | json}}
, you'll also see the view update when the array changes. (This is because the JsonPipe is stateful, which causes Angular change detection to evaluate it every change detection cycle.)
Upvotes: 4