Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two-Way bind Single Object Observable

Tags:

angular

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?

like image 573
Botonomous Avatar asked Dec 29 '17 20:12

Botonomous


2 Answers

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.

like image 145
Zlatko Avatar answered Sep 18 '22 13:09

Zlatko


out of interest is this.load visible to the component or should it be:

  fetchLoad= (loadid : number): void =>{
  this.load = this.loadService.apiLoadByIdGet(loadid);
  }
like image 25
oudekaas Avatar answered Sep 18 '22 13:09

oudekaas