0

我有一个表格,有最少的字符和最多的字符,问题是如果最小值是 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

4

2 回答 2

1

使用表单提交

<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>

组件.ts

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

示例堆栈闪电战

在此处输入图像描述

于 2020-01-13T11:29:01.690 回答
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>
于 2020-01-13T11:25:26.107 回答