typescript - Angular 2 Children components detect changes in parent -
i have component displays list of 'items' components created selector. have checkbox want, when clicked update 'state' of child components.
im struggling find correct solution doing this. please see plunkr more info.
//our root app component import {component, eventemitter} 'angular2/core' class item { name: boolean; constructor(name: string) { this.name = name; } } @component({ selector: 'my-item', template: ` <div> <label><input type="checkbox" [(ngmodel)]="state"/> {{state}}</label> </div> ` }) export class myitemcomponent { state: boolean = false; } @component({ selector: 'my-app', template: ` <div style="border: 1px solid red;"> <label><input type="checkbox" [(ngmodel)]="state"/> {{state}}</label> </div> <div *ngfor="#item of items"> <my-item></my-item> </div> `, directives: [myitemcomponent] }) export class app { state: boolean = true; items: item[] = []; constructor() { this.items.push(new item("hello")); this.items.push(new item("test")); } }
update
@component({ selector: 'my-item', inputs: ['state']; // added template: ` <div> <label><input type="checkbox" [(ngmodel)]="state"/> {{state}}</label> </div> ` }) export class myitemcomponent { state: boolean = false; }
and use like
<my-item [state]="state"></my-item>
original
angular change detection doesn't detect changes in arrays.
should make work:
constructor() { this.items.push(new item("hello")); this.items.push(new item("test")); this.items = this.items.slice(); }
this way new array (a copy) assigned this.items
, therefore angular recognize change.
in myitem
need input
@component({ selector: 'my-item', inputs: ['items']; // added template: ` <div> <label><input type="checkbox" [(ngmodel)]="state"/> {{state}}</label> </div> ` }) export class myitemcomponent { state: boolean = false; items: item[]; // added }
then build connection with
<my-item [items]="items"></my-item>
to code called in myitemcomponent
when items
change implement ngonchanges()
see https://angular.io/docs/ts/latest/api/core/onchanges-interface.html
export class myitemcomponent { state: boolean = false; items: item[]; // added ngonchanges(changes: {[propname: string]: simplechange}) { console.log('ngonchanges - myprop = ' + changes['items'].currentvalue); } }
Comments
Post a Comment