What is the `change` event in Angular 2

What is a change event in Angular 2? When is it sent and how can I use it?
I. e. What did I sign in the following code via (change)="update()" ?

http://plnkr.co/edit/mfoToOSLU6IU2zr0A8OB?p=preview

 import {Component, View, Input, Output, EventEmitter, OnChanges} from '@angular/core' @Component({ selector: 'inner-component', template: ` <label><input type="checkbox" [(ngModel)]="data.isSelected"> Selected</label> ` }) export class InnerComponent { data = { isSelected: false }; } @Component({ selector: 'my-app', template: ` <p><inner-component (change)="update()"></inner-component></p> <p>The component was updated {{count}} times</p> `, directives: [InnerComponent] }) export class AppComponent { count = 0; update() { ++this.count; } } 

PS: The same question in Russian .

+6
source share
2 answers

This event bubbles up: change occurs on input , then bubbles up the dom tree and is processed by the inner-component element. It can be checked by registering and events:

http://plnkr.co/edit/J8pRg3ow41PAqdMteKwg?p=preview

 @Component({ selector: 'my-app', template: ` <p><inner-component (change)="update($event)"></inner-component></p> <p>The component was updated {{count}} times</p> `, directives: [InnerComponent] }) export class AppComponent { count = 0; update($event) { console.log($event, $event.target, $event.currentTarget); ++this.count; } } 
+12
source

The change event notifies you of a change in the input field. Since your internal component is not a native Angular component, you must specify the event emitter yourself:

 @Component({ selector: 'inner-component', template: ` <label><input type="checkbox" (change)="inputChange.emit($event)" [(ngModel)]="data.isSelected"> Selected</label> ` }) export class InnerComponent { @Output('change') inputChange = new EventEmitter(); data = { isSelected: false }; } 

And in your AppComponent you now get events:

 @Component({ selector: 'my-app', template: ` <p><inner-component (change)="update($event)"></inner-component></p> <p>The component was updated {{count}} times</p> `, directives: [InnerComponent] }) export class AppComponent { count = 0; update(event: any) { ++this.count; console.log(event); } } 
+3
source

All Articles