2017-02-11 122 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