Reputation: 765
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
});
}
}
And here's my 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)]?
Upvotes: 1
Views: 497
Reputation: 657957
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
}
}
Upvotes: 3