双向绑定单对象 Observable

Bot*_*ous 4 angular

我想对 Angular 4 中的元素执行双向数据绑定,但我遇到了问题。任何人都可以提供一些方向吗?

成分:

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

模板:

   <div>
        Cartons: {{(load | async)?.cartons}} <input type="range" [(ngModel)]="(load | async)?.cartons.value" max="1000" value="{{(load | async)?.cartons}}">     
    </div>
Run Code Online (Sandbox Code Playgroud)

我希望对输入滑块所做的更改反映在模型中。这一行: Cartons: {{(load | async)?.cartons}}

显示当前值,但是当调整滑块时,该值似乎没有变化。

我也尝试过使用但ngModelChange没有运气。

有任何想法吗?

Zla*_*tko 5

好吧,你不能在那里有管道,所以你必须将双向绑定拆分为两个单向绑定:

<input type="range" [ngModel]="(load | async)?.cartoons.value" (ngModelChange)="loadValueChange($event)">
Run Code Online (Sandbox Code Playgroud)

现在,在您的组件中创建一个loadValueChange(newValue)方法来更新您的 observable 上的值。