简体   繁体   English

使用Angular2进行双向数据绑定

[英]Two-Way Data-Binding with Angular2

Does anybody know what I'm doing wrong here? 有谁知道我在这里做错了什么? I'm unable to get Angular2 2-way data-binding to work using the [(ngModel)] syntax. 我无法使用[(ngModel)]语法使Angular2双向数据绑定工作。 Here's my Component: 这是我的组件:

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

And here's my HTML: 这是我的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>

Shouldn't changing the value of this.progress inside the Component reflect in the view since I'm using [(ngModel)]? 因为我正在使用[(ngModel)],所以不应该更改组件内部的this.progress值反映在视图中?

For two-way-binding you need an @Input() and and @Output() where the name matches while the @Output() s name has an additional Change suffix. 对于双向绑定,您需要@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
    });
  }
}

for the event handler you can also use 对于事件处理程序,您也可以使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM