【问题标题】:Combine multiple form control observables and subscribe in a reactive form组合多个表单控件可观察对象并以反应形式订阅
【发布时间】:2019-09-24 10:17:12
【问题描述】:

我有一个包含多个输入字段的表单(例如:CID、LastName、FirstName 等)。要求是在表单提交时提供一个输入。因此,在任何字段中输入输入时,需要清除输入字段以外的字段中的值

我计划使用 Rxjs 中的一些运算符来组合它并仅使用一个订阅,而不是为所有控件订阅 valuechanges。我发现的是 combineLatest。所以我只是把所有的控件都推到一个数组中,并计划传递给 combineLatest 操作符。

我创建了一个堆栈闪电战。 https://stackblitz.com/edit/angular-xeqms6?file=src%2Fapp%2Fapp.component.ts

handleFormChanges(){

    const controlArr=[];
    for (const field in this.formControls) {
      controlArr.push(this.formEl.get(field).valueChanges);
    }

      combineLatest(controlArr)
       .pipe(map(control=>{
         startWith('')
        return control;
       }))
      .subscribe((value)=>{

        // Here I need to write the logic to clear input fields other than the current one.
        console.log(value);

      })
  }

上面代码的问题是,只有在所有字段中至少输入一次值后,才会首先触发订阅。后续触发器按预期工作。

我需要的是在每个 valuechanges 订阅回调需要被调用

【问题讨论】:

  • 也请分享你的代码链接,你的stackblitz链接没有你写的代码
  • 对不起,我的错。这是链接 [链接] (stackblitz.com/edit/…)
  • 你为什么不订阅yourform.valueChanges?不需要逐个字段
  • 是的,你是对的,我不知道为什么我没有想到这一点。感谢您的提示

标签: angular rxjs


【解决方案1】:
  handleFormChanges() {
this.formEl.valueChanges
  .pipe(pairwise())
  .subscribe(([prev, current]) => {
    for (const field in prev) {
      if (prev[field] === current[field]) {
        this.formEl.get(field).setValue(null, { onlySelf: true });
      }
    }
  });

}

https://stackblitz.com/edit/angular-xeqms6

【讨论】:

  • 正是我需要的。使用pairwise operator对我来说是一个新的学习。谢谢你。
  • 祝您旅途愉快。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-26
  • 1970-01-01
相关资源
最近更新 更多