什么是Angular 2中的`change`事件

时间:2016-07-06 15:28:35

标签: typescript angular

Angular 2中的change事件是什么?什么时候发货?如何使用? I. e。我通过(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 个答案:

答案 0 :(得分:13)

该事件冒泡:changeinput上发生,然后在dom树下冒泡并在inner-component元素上处理。可以通过记录事件来检查:

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

答案 1 :(得分:5)

change事件会通知您输入字段中发生的更改。由于您的内部组件不是本机Angular组件,因此您必须自己指定事件发射器:

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

在您的AppComponent中,您现在正在接收事件:

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

答案 2 :(得分:0)

这只是一个事件发射器。例如,如果您查看Angular mat设计的mat-select的{​​{3}},则可以看到,但在这种情况下,selectionChange

@Output() readonly selectionChange: EventEmitter<MatSelectChange> =
      new EventEmitter<MatSelectChange>();