What is `change` event in Angular 2

2020-06-12 02:29发布

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;
  }
}

PS: Same question in Russian.

3条回答
家丑人穷心不美
2楼-- · 2020-06-12 02:54

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:

@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're now receiving the 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楼-- · 2020-06-12 03:01

That's event bubbling: change occures on input, then bubbles by dom tree and gets handled on inner-component element. It can be checked by logging an event:

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;
  }
}
查看更多
欢心
4楼-- · 2020-06-12 03:01

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

@Output() readonly selectionChange: EventEmitter<MatSelectChange> =
      new EventEmitter<MatSelectChange>();
查看更多
登录 后发表回答