使用Angular2进行双向数据绑定

时间:2017-02-11 22:07:08

标签: angular

有人知道我在这里做错了什么吗?我无法使用[(ngModel)]语法使Angular2双向数据绑定工作。这是我的组件:

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
declare let window;

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {
  progress: number;

  constructor(public _sharedService: SharedService) {
    window.addEventListener('progress.update', function () { # ANSWER: Change function () { to () => {
      this.progress = window.sharedService.progress;
      console.log(this.progress); # this outputs numbers
    });
  }
}

这是我的HTML:

<ion-range [(ngModel)]="progress" min="0" max="100" name="progress">
        <ion-icon range-left small name="sunny"></ion-icon>
        <ion-icon range-right name="sunny"></ion-icon>
      </ion-range>

由于我使用[(ngModel)],因此不应该在视图中反映Component内部的this.progress值吗?

1 个答案:

答案 0 :(得分:3)

对于双向绑定,您需要@Input()@Output(),其中名称匹配,而@Output()的名称后缀为Change

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {
  @Input()
  progress: number;

  @Output()
  progressChange:EventEmitter<number> = new EventEmitter<number>();

  constructor(public _sharedService: SharedService) {
    window.addEventListener('progress.update', () => { // <<<=== use arrow function for `this.` to work
      this.progress = window.sharedService.progress;
      this.progressChange.emit(this.progress);
      console.log(this.progress); # this outputs numbers
    });
  }
}

对于事件处理程序,您也可以使用

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {
  @Input()
  progress: number;

  @Output()
  progressChange:EventEmitter<number> = new EventEmitter<number>();

  constructor(public _sharedService: SharedService) {}

  @HostListener('window:progress.update')
  onProgressUpdate() {
    this.progress = window.sharedService.progress;
    this.progressChange.emit(this.progress);
    console.log(this.progress); # this outputs numbers
  }
}