Angular2的双向数据绑定 [英] Two-Way Data-Binding with Angular2

查看:55
本文介绍了Angular2的双向数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道我在做什么错吗?我无法使用[[ngModel)]语法使Angular2 2路数据绑定正常工作.这是我的组件:

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

这是我的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的值反映在视图中吗?

Shouldn't changing the value of this.progress inside the Component reflect in the view since I'm using [(ngModel)]?

推荐答案

对于双向绑定,您需要一个 @Input() @Output(),其中名称匹配而 @Output()的名称具有一个附加的 Change 后缀.

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.

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

这篇关于Angular2的双向数据绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆