What is change
event in Angular 2? When is it dispatched and how can I use it?
I. e. what have I subscribed in 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;
}
}
The
change
event notifies you about a change happening in an input field. Since your inner component is not a native Angular component, you have to specifiy the event emitter yourself:And in your AppComponent you're now receiving the events:
That's event bubbling:
change
occures oninput
, then bubbles by dom tree and gets handled oninner-component
element. It can be checked by logging an event:http://plnkr.co/edit/J8pRg3ow41PAqdMteKwg?p=preview
It is just an event emitter. For example if you take a look at Angular mat design's source code for
mat-select
you can see, but in this case,selectionChange