即使出现错误也可以完美提交

When submitting is done perfectly even if errors come out

我有一个表格,有最少的字符数和最多的字符数,问题是如果最少有 2 个字符,我放了一个我得到了 mat-error 但是当给它保存时,你只能用一个字符。

 <mat-form-field>
        <input matInput #input1 maxlength="300" minlength="2"
                placeholder="Nombre"
               formControlName="name">
        <mat-hint align="end">{{input1.value?.length || 0}}/300</mat-hint>
        <mat-error>
           Minimo 2 caracteres máximo 300
        </mat-error>
</mat-form-field>

保存按钮:

 <button  class="mat-raised-button mat-primary"  (click)="save()">Save</button>

保存函数:

    save() {
    this.dialogRef.close(this.form.value);
  }

https://stackblitz.com/edit/angular-jkjrsd-8flxvt

验证应该在表单控件中。您必须从 HTML maxlength="300" minlength="2" 中删除并在表单组中设置表单验证,例如:

.ts

formGroup = new FormGroup({
    name: new FormControl('', [Validators.maxLength(300), Validators.minLength(2), Validators.required])
  });

.html

<form (ngSubmit)="onSubmit()" [formGroup]="formGroup">
    <mat-form-field>
        <input matInput #input1 placeholder="Nombre" formControlName="name">
        <mat-hint align="end">{{input1.value?.length || 0}}/300</mat-hint>
        <mat-error>
           Minimo 2 caracteres máximo 300
        </mat-error>
    </mat-form-field>
    <button type="submit" [disabled]="!formGroup.valid">Save</button>
</form>

使用表单提交

<form [formGroup]="form" (ngSubmit)="save()" class="example-form">
<mat-form-field>
    <input matInput #input1 maxlength="300" minlength="2"
            placeholder="Nombre"
           formControlName="name">
    <mat-hint align="end">{{input1.value?.length || 0}}/300</mat-hint>
    <mat-error>
        Minimo 2 caracteres máximo 300
    </mat-error>
</mat-form-field>
<button type="submit"> save</button>

component.ts

save(){
  if(this.form.valid){
  console.log('saved')
  }
  else{
     console.log('invalid form')
  }
}

示例stackblitz