Responding to Component Events

An event handler is specified inside the template using round brackets to denote event binding. This event handler is then coded in the class to process the event.

  1. import {Component} from '@angular/core';
  2. @Component({
  3. selector: 'rio-counter',
  4. template: `
  5. <div>
  6. <p>Count: {{num}}</p>
  7. <button (click)="increment()">Increment</button>
  8. </div>
  9. `
  10. })
  11. export class CounterComponent {
  12. num = 0;
  13. increment() {
  14. this.num++;
  15. }
  16. }

View Example

To send data out of components via outputs, start by defining the outputs attribute. It accepts a list of output parameters that a component exposes to its parent.

app/counter.component.ts

  1. import { Component, EventEmitter, Input, Output } from '@angular/core';
  2. @Component({
  3. selector: 'rio-counter',
  4. templateUrl: 'app/counter.component.html'
  5. })
  6. export class CounterComponent {
  7. @Input() count = 0;
  8. @Output() result = new EventEmitter<number>();
  9. increment() {
  10. this.count++;
  11. this.result.emit(this.count);
  12. }
  13. }

app/counter.component.html

  1. <div>
  2. <p>Count: {{ count }}</p>
  3. <button (click)="increment()">Increment</button>
  4. </div>

app/app.component.ts

  1. import { Component, OnChange } from '@angular/core';
  2. @Component({
  3. selector: 'rio-app',
  4. templateUrl: 'app/app.component.html'
  5. })
  6. export class AppComponent implements OnChange {
  7. num = 0;
  8. parentCount = 0;
  9. ngOnChange(val: number) {
  10. this.parentCount = val;
  11. }
  12. }

app/app.component.html

  1. <div>
  2. Parent Num: {{ num }}<br>
  3. Parent Count: {{ parentCount }}
  4. <rio-counter [count]="num" (result)="ngOnChange($event)">
  5. </rio-counter>
  6. </div>

View Example

Together a set of input + output bindings define the public API of your component. In our templates we use the [squareBrackets] to pass inputs and the (parenthesis) to handle outputs.

原文: https://angular-2-training-book.rangle.io/handout/components/app_structure/responding_to_component_events.html