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

问题描述 投票:0回答:2

我有一个表单,具有最少的字符和最多的字符,问题是,如果最少的字符是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);
  }
angular modal-dialog mat-input mat-error
2个回答
0
投票

使用表单提交

<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

enter image description here


0
投票

验证应在表单控件中。您必须从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>
© www.soinside.com 2019 - 2024. All rights reserved.