I want to perform two-way data binding on an element in Angular 4 but I'm having problems. Can anyone provide some direction?
Component:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Load } from '../services/model/load';
import { LoadService } from '../services/api/load.service';
import {Observable} from 'rxjs/Observable';
@Component({
selector: 'app-storeedit',
templateUrl: './storeedit.component.html',
styleUrls: ['./storeedit.component.css']
})
export class StoreeditComponent implements OnInit {
load: Observable<Load>;
private sub: any;
constructor(private route: ActivatedRoute, private loadService: LoadService) { }
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
// Require ID
var loadId : number = +params['id'];
this.fetchLoad(loadId);
})
}
fetchLoad(loadid : number): void {
this.load = this.loadService.apiLoadByIdGet(loadid);
}
ngOnDestroy() {
//Called once, before the instance is destroyed.
this.sub.unsubscribe();
}
}
Template:
<div>
Cartons: {{(load | async)?.cartons}} <input type="range" [(ngModel)]="(load | async)?.cartons.value" max="1000" value="{{(load | async)?.cartons}}">
</div>
I want changes made on the input slider to reflect in the model.
This line: Cartons: {{(load | async)?.cartons}}
Shows the current value, but when the slider is adjusted, the value does not seem to change.
I have tried also using ngModelChange
with no luck.
Any ideas?
Well, you cannot have pipes there so you have to split the two-way binding to two one-way bindings:
<input type="range" [ngModel]="(load | async)?.cartoons.value" (ngModelChange)="loadValueChange($event)">
Now, in your component make a loadValueChange(newValue)
method that will update the value on your observable.
out of interest is this.load visible to the component or should it be:
fetchLoad= (loadid : number): void =>{
this.load = this.loadService.apiLoadByIdGet(loadid);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With