Angular 组件加载时响应式表单的 7 个设置值启用保存按钮,即使表单未经过验证

Angular 7 setting values of reactive form on component load enable save button even if the form isn't validated

我有以下问题。 Click to check the stack blitz.

我在构造函数中设置反应形式:

this.formGroup = this.fb.group({
      'family_name_en': new FormControl('', Validators.required),
      'family_name_ar': new FormControl('', [Validators.required, Validators.pattern('[\u0600-\u06FF ]*')]),
      'unit_id': new FormControl({ value: '', disabled: true }, [Validators.required])
});

并且在 ngOnInti() 挂钩中,我正在获取与 unit_id.

相关的数据

由于我正在将数据从一个平台迁移到另一个平台,因此不推荐使用阿拉伯语的姓氏,但现在推荐使用。因此大部分数据将在没有阿拉伯名称的情况下加载。

问题是按钮始终处于启用状态,我需要做的是如果用户想要更新此 unit_id,他应该添加阿拉伯语名称以便按钮启用。

如果表单有效,则在加载组件时启用按钮不会有任何危害。

这是获取数据和设置表单组控件值的getData()方法:

ngOnInit() {
    this.getDataById();
}

getDataById():

getDataById() {
    this.showSpinner = true;
    this.auth.getDataById(this.unit_id).subscribe(
      (data) => {
        if (data['info'][0]['total'] == 1) {
          this.noDataBool = false;
          this.showSpinner = false;
          this.family_name_en = data['info'][0]['hh_last_name_en'];
          this.formGroup.controls['family_name_en'].setValue(this.family_name_en);
          this.family_name_ar = data['info'][0]['hh_last_name_ar'];
          this.formGroup.controls['family_name_ar'].setValue(this.family_name_ar);
          this.unit_id = data['info'][0]['unit_id'];
          this.formGroup.controls['unit_id '].setValue(this.unit_id);
    }
}

按钮:

<button mat-raised-button color="warn" (click)="updateData()" [disabled]="!formGroup.valid">
    <mat-icon>update</mat-icon>Update
</button>

我总是在这种情况下使用以下代码:

this.family_name_ar.setValue(data['info'][0]['hh_last_name_ar']);
this.family_name_ar.updateValueAndValidity();

通过调用第二种方法,updateValueAndValidity()我们把Angular告诉

Recalculate the value and validation status of the control.

有关 Angular Docs 的更多信息。

现在,如果 data['info'][0]['hh_last_name_ar'] 为空,按钮应该被禁用并且表单无效。

您可以对每个需要的字段使用上述方法。

与其在 formGroup 上使用 controls 直接访问 FormControl,不如在它们上使用 get API。这会给你更多的控制权并显着清理你的实现(特别是在获得深层嵌套元素的情况下)。您可以像这样更改组件实现:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  formGroup: FormGroup;
  titleAlert: string = 'This field is required';
  post: any = '';
  family_name_en;
  family_name_ar;
  unit_id;
  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.formGroup = this.fb.group({
      'family_name_en': new FormControl('', Validators.required),
      'family_name_ar': new FormControl('', [Validators.required, Validators.pattern('[\u0600-\u06FF ]*')]),
      'unit_id': new FormControl({ value: '', disabled: true }, [Validators.required])
    });
    this.getDataById();
  }

  getDataById() {
    let data: Array<any> = [
      'Ali', '', '123'
    ]
    this.family_name_en = data[0];
    this.formGroup.get('family_name_en').setValue(this.family_name_en);
    this.family_name_ar = data[1];
    this.formGroup.get('family_name_ar').setValue(this.family_name_ar);
    this.unit_id = data[2];
    this.formGroup.get('unit_id').setValue(this.unit_id);
  }

}

这里有一个 Updated StackBlitz 供您参考。您可以通过在其中输入 علي 来测试它,这将启用“更新”按钮。输入 Ali 将让它保持禁用状态。