【问题标题】:Angular Reactive Form Programmatic SetterAngular 反应式表单编程设置器
【发布时间】:2017-09-12 21:17:41
【问题描述】:

我有一个带有验证的Angular Reactive Form。 为我的hiddenComposedField 调用设置器的正确方法是什么?

component.ts

ngOnInit() {
  this.myForm = this.formBuilder.group({
    'field1': ['', [Validators.required]],
    'field2': ['', [Validators.required]],
    'hiddenComposedField': [''],
  });

  this.myForm.get('field1').valueChanges.subscribe((val) => {
     this.setHiddenComposedField();
  });
  this.myForm.get('field2').valueChanges.subscribe((val) => {
     this.setHiddenComposedField();
  });
}

setHiddenComposedField() {
    let field1 = this.myForm.get('field1').value;
    let field2 = this.myForm.get('field2').value;

    // This doesn't work, but I want something like it:
    this.myForm.set('hiddenComposedField',field1 + ' ' + field2); // :(
}

component.html

<form [formGroup]="myForm">
  <input formControlName="field1">
  <input formControlName="field2">
  <!-- NB: hiddenComposedField is not exposed to the user; -->
  <!--     it is only on the submitted form model. -->
  <button type="submit">Submit</button>
</form>

【问题讨论】:

    标签: angular validation reactive-programming


    【解决方案1】:

    这样的事情应该可以工作,以便您首先获取 Control,然后设置它的值。

    this.myForm.get('hiddenComposedField').setValue(field1 + ' ' + field2);
    

    【讨论】:

      【解决方案2】:

      使用字符串插值的方式略有不同

      setHIddenField(){
       const field1 = this.myForm.get('field1').value;
       const field2 = this.myForm.get('field2').value;
       const separator= ' --- ';
       let result = `${field1} ${separator} ${field2}`;
       this.myForm.get('hiddenComposedField').setValue(result);
      }
      

      这是StackBlitz 链接。

      【讨论】:

        【解决方案3】:

        这个问题的最终解决方案是订阅表单控件的valueState。

        import { combineLatest } from 'rxjs';
        
        const firstName = new FormControl();
        const lastName = new FormControl();
        const fullName = new FormControl();
        
        combineLatest([firstName.valueChanges, lastName.valueChanges])
                .subscribe(([firstName, lastName]) => 
                             fullName.setValue(firstName + " " + lastName)
        ); 
        
        firstName.setValue('Ahmet');
        lastName.setValue('Emrebas');
           
        console.log(fullName.value); // OUTPUT : Ahmet Emrebas
             
        
        

        每当您更改表单中的值时,c 字段都会自动更新。

        这是解决此类问题的最合适的方法。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-07-22
          • 2018-11-02
          • 2019-06-24
          • 2019-03-14
          • 2021-01-12
          • 1970-01-01
          • 2020-11-24
          • 2019-08-11
          相关资源
          最近更新 更多