Angular 7-使用FormControl字段启用提交表单

问题描述

我的FormGroup具有3个字段:2个文本字段和1个FormControl。

所有字段都是必填字段,并且FormControl具有一个特定的Validator:

generateForm(scanfolder) {
console.log('generateForm');
this.origineControl.setValidators(this.forbiddenNamesValidator(this.options))
const fb: FormBuilder = new FormBuilder();
this.scanfolderForm = fb.group({
  'fullpath': [scanfolder.fullpath,[Validators.required]],'name': [scanfolder.name,'origin': [this.origineControl,});
}

特定控件:

forbiddenNamesValidator(names: string[]): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } | null => {
  console.log(typeof control );
  console.log(control.value );
  // below findindex will check if control.value is equal to one of our options or not
  const index = names.findindex(name => {
    return (new RegExp('\^' + name + '\$')).test(control.value);
  });
  return index < 0 ? { 'forbiddenNames': { value: control.value } } : null;
};
}

填充字段后,必须启用“提交表单”按钮,但此按钮不起作用:

之前

enter image description here

之后:

enter image description here

我们可以看到按钮可用,而第二场有错误

这是我的HTML:

          <form [formGroup]="scanfolderForm">
        <div class="row">
          <mat-form-field class="col-md-4">
            <input matInput placeholder="Chemin complet"  formControlName="fullpath" name="fullpath">
            <mat-error *ngIf="scanfolderForm.controls['fullpath'].errors?.incorrectName">Saisie incorrecte</mat-error>
          </mat-form-field>
          <mat-form-field class="col-md-4">
            <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="origineControl" [matAutocomplete]="auto" required>
            <mat-autocomplete #auto="matAutocomplete">
              <mat-option *ngFor="let option of options" [value]="option">
                {{option}}
              </mat-option>
            </mat-autocomplete>
            <mat-error *ngIf="origineControl.hasError('forbiddenNames')">
              You should enter value from suggested one only. <strong>'{{origineControl.errors.forbiddenNames.value}}'</strong> is not allowed.
            </mat-error>
            <mat-error *ngIf="origineControl.hasError('required')">
              This is <strong>required</strong>
            </mat-error>
          </mat-form-field>
          <mat-form-field class="col-md-4">
          <input matInput placeholder="Nom" formControlName="name" name="name">
          </mat-form-field>
        </div>
     </form>
    

<mat-dialog-actions *ngIf="!loading">
 <button class="btn btn-primary" *ngIf="action === 2 && !isdisabled" (click)="cuScanfolder()" 
  [disabled]="!scanfolderForm.valid">M.A.J</button>
  <button class="btn btn-warning" *ngIf="data.list.length < 2" (click)="nextOne()" cdkFocusInitial>Retour</button>
</mat-dialog-actions>

解决方法

来自official

在运行时添加或删除验证器时,必须调用updateValueAndValidity()才能使新验证生效。

this.origineControl.setValidators([this.forbiddenNamesValidator(this.options),Validators.required]);
const fb: FormBuilder = new FormBuilder();
this.scanfolderForm = fb.group({
  'fullpath': [scanfolder.fullpath,[Validators.required]],'name': [scanfolder.name,[Validators.required]]
});
this.scanfolderForm.addControl('origin',this.origineControl)
this.scanfolderForm.updateValueAndValidity();
<mat-form-field class="col-md-4">
  <input type="text" placeholder="Pick one" aria-label="Number" matInput formControlName="origin" [matAutocomplete]="auto" required>
  <mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngFor="let option of options" [value]="option">
      {{option}}
    </mat-option>
  </mat-autocomplete>
  <mat-error *ngIf="scanfolderForm.get('origin').hasError('forbiddenNames')">
    You should enter value from suggested one only. <strong>'{{scanfolderForm.get('origin').errors.forbiddenNames.value}}'</strong> is not allowed.
  </mat-error>
  <mat-error *ngIf="scanfolderForm.get('origin').hasError('required')">
    This is <strong>required</strong>
  </mat-error>
</mat-form-field>