JustDoItTomorrow
3/6/2018 - 6:53 AM

模板语法:双向绑定

解开双向绑定语法糖

<!--写法1,这是双向绑定真正的样子-->
<app-sizer [size]="fontSizePx" (sizeChange)="fontSizePx=$event"></app-sizer>

<!--写法2,这是双向绑定的简写-->
<app-sizer [(size)]="fontSizePx"></app-sizer>
import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'app-sizer',
  template: `
  <div>
    <button (click)="dec()" title="smaller">-</button>
    <button (click)="inc()" title="bigger">+</button>
    <label [style.font-size.px]="size">FontSize: {{size}}px</label>
  </div>`
})
export class SizerComponent {
  @Input()  size: number | string;
  @Output() sizeChange = new EventEmitter<number>();

  dec() { this.resize(-1); }
  inc() { this.resize(+1); }

  resize(delta: number) {
    this.size = Math.min(40, Math.max(8, +this.size + delta));
    this.sizeChange.emit(this.size);
  }
}