mat-error 不会显示在 mat-autocomplete 和 mat-form-field 中

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

我的目的是当用户未输入值时显示错误。我知道上面的例子没有多大意义,但如果程序必须显示,我也不会读取错误。代码是这样的:

<form (ngSubmit)="ricerca()" #formCampiRicerca="ngForm">

    <mat-form-field appearance="legacy" class="col-sm-12 col-lg-6 w-100 p-3">
        <mat-label>{{ "APPLICATION......" | }}</mat-label>
    
        <input type="text" [(ngModel)]="flux" class="modInput" #flux="ngModel">
    
        <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
            <ng-container *ngIf="existsFlux()">
                ...
            </ng-container>
    
        </mat-autocomplete>
        // here the error doesn't show also it doesn't have a filed
        <mat-error>minlength 4</mat-error>
    
    </mat-form-field>
</form>

在我的模块中我导入:

 CommonModule,
    RicercaCircolariRoutingModule,
    ReactiveFormsModule,
    FormsModule,
    MatFormFieldModule,
    MatInputModule,
    MatSelectModule,
    MatAutocompleteModule,
    MatDialogModule,

垫子错误没有显示,也没有条件。有人可以帮助我吗?我没有读到错误消息“minlength 4”

angular angular-material angular-forms angular-template-form
2个回答
0
投票

我建议不要为

NgModel
指定与模板中使用的另一个属性相同的名称。我首先会更改该名称,然后仅在需要时显示错误。

如果您希望某字段为必填字段,只需添加

required
属性即可。

<form (ngSubmit)="ricerca()" #formCampiRicerca="ngForm">
    <mat-form-field appearance="legacy" class="col-sm-12 col-lg-6 w-100 p-3">
        <mat-label>{{ "APPLICATION......" | }}</mat-label>
        <input type="text" required [(ngModel)]="flux" class="modInput" #fluxModel="ngModel">

        <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
            <ng-container *ngIf="existsFlux()">
                ...
            </ng-container>
    
        </mat-autocomplete>
        <mat-error *ngIf="fluxModel.control.hasError('required')">
          This field is required
        </mat-error>
    </mat-form-field>
</form>

0
投票

对我来说,解决方案是在自动完成功能的搜索控件上使用

markAsTouched

<mat-form-field appearance="outline">
    <input type="text"
      [placeholder]="placeholder"
      aria-label="Number"
      matInput
      #autoInput
      [formControl]="searchCtrl"
      [matChipInputFor]="chipList"
      [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="select($event)">

    ....

    @if (searchCtrl.hasError('test')) {
      <mat-error>This field is required</mat-error>
    }
</mat-form-field>

所以在控制器的函数中,我可以做类似的事情

this.searchCtrl.markAsTouched();
this.searchCtrl.setErrors({test:true })

它会向我显示错误:

添加

markAsTouched
是其发挥作用的关键。

© www.soinside.com 2019 - 2024. All rights reserved.