2017-02-11 97 views
1

有人知道我在这里做错了吗?我无法使用[(ngModel)]语法使Angular2 2-way数据绑定工作。这里是我的组件:双向数据绑定与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> 

不应该改变内部组件的this.progress值反映的观点,因为我使用的是[(ngModel)] ?

+0

也许是因为'progress'型'number'的?你可以让它'串'并尝试?我不确定如果你提供plunkr会很好。 – narainsagar

+0

刚刚检查,进度是一个数字 – user2476265

回答

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 
    } 
} 
+0

HTML的样子是什么?此外,这是否会打败[(ngModel)]的目的? – user2476265

+1

不确定你的意思是HTML。 '[(ngModel)]'做双向绑定。这在视图中应该反映在哪里? –

+0

不应该双向数据绑定已经将它绑定到组件类? – user2476265