【问题标题】:How to get values from disabled form controls in a form group as Stream ? ( like the valueChanges method)如何从表单组中的禁用表单控件中获取值作为 Stream ? (如 valueChanges 方法)
【发布时间】:2020-02-03 20:13:19
【问题描述】:

在表单组中禁用 Angular 的 FormControl 的常规行为是省略控制器的键/值。 但我需要保留表单对象结果的结构 - 所以我需要禁用控制器的键出现在最终表单值对象中。

有一个简单的解决方案可以使用“getRowValue()”方法获取它,但它不是流... 有没有一种内置的方法可以将它放入流中?

例子

myForm = new FormGroup({   
    name:new FormControl({value:'',disabled:true}),
    power:new FormControl('')
  })

valueChanges() {power:anyValue} 的结果

我需要 {power:anyValue ,name:""}

example in stackblitz

【问题讨论】:

    标签: angular angular-reactive-forms


    【解决方案1】:

    在你的组件中添加这样的东西:

    rawValueChanges = this.myForm.valueChanges.pipe(
      map(_ => this.myForm.getRawValue())
    )
    

    查看working example in StackBlitz

    【讨论】:

      【解决方案2】:

      我们的想法是将表单的最后状态“保存”在每次更新表单时都会更新的属性中:

        public formSave = null;
      
        ...
      
        ngAfterViewInit() {
          if (!this.formSave) {
            setTimeout(() => {
              this.formSave = this.myForm.value;
            });
          }
      
          this.myForm.valueChanges.subscribe(newVal => {
            console.log('changes', newVal);
            this.formSave = {...this.formSave, ...newVal};
          });
        }
      

      一些解释:

      {...this.formSave, ...newVal}(称为spread operator)采用原始保存的表单值(与您的禁用值,以防它已被禁用)并合并valueChanges流返回的新值。

      为什么是setTimeout()?这只是为了避免ExpressionChangedAfterItHasBeenCheckedError,因为我们正在修改lifecycle hook 中的类属性。因此,为了触发新的循环检查,我将属性初始化放在此语句中。但您也可以使用 ChangeDetectorRef 解决此问题(但这是题外话)。

      由于只返回启用的值,因此不会更改禁用字段的值。

      Here's your working StackBlitz app

      【讨论】:

        猜你喜欢
        • 2018-09-15
        • 1970-01-01
        • 1970-01-01
        • 2016-09-24
        • 1970-01-01
        • 1970-01-01
        • 2017-08-06
        • 2017-12-07
        • 1970-01-01
        相关资源
        最近更新 更多