我们可以在 Angular 的 *For* 循环中使用 <mat-error></mat-error>吗

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

我创建了一个通用组件。我陷入了一个问题,我正在使用有角度的材料并使用垫子形式场。我在 Angular 18 中使用 @if 来检查条件,然后 mat-error 工作正常。但是当我使用 @for 时它不起作用并且 mat-error 显示在输入字段内而不是 mat-error 中。我还需要这样写我的条件:

以上是我正在寻找的所需格式。但我也尝试使用单个@if和@for。但@for 不起作用。 这是我使用 @for 时的输出:

  1. 第一张图片显示输入内部出现错误与 mat-error 一起使用时的循环输出
@if(condition){
    @for(condition){
        <mat-error>{{error}}</mat-error>
    }
}

    <mat-form-field>
        <mat-label >{{label}}</mat-label>
            <input matInput [ngClass]="{'is-invalid': this.formGroup.get(controlName)?.invalid && this.formGroup.get(controlName)?.touched}" [formControlName]="controlName" (focus)="triggerValidation(controlName)" [required]="required" [type]="type" [placeholder]="placeholder">
                 @if(formGroup.get(controlName)?.invalid && formGroup.get(controlName)?.touched){
                     @for(error of getErrorMessages(controlName); track i; let i = $index){
                         <mat-error> {{ error }} </mat-error >
                      }
    }
    </mat-form-field>

我尝试使用 ng-container。但现在 ng-container 没有用,因为我们有 @if 和 @for 块。 我正在使用 @if 和 @else 寻找以下输出:

  1. 这是我的图像的输出:

预期输出,目前我只使用了@if,所以我得到了这个输出

我期待的输出

angular angular-material angular-directive angular18
1个回答
0
投票

我不知道你为什么要@for for 。您只需拨打 .

 上的 
getErrorMessages(controlName)

即可
<mat-form-field>
  <mat-label>{{label}}</mat-label>
  <input matInput [ngClass]="{'is-invalid': this.formGroup.get(controlName)?.invalid && this.formGroup.get(controlName)?.touched}"
    [formControlName]="controlName" (focus)="triggerValidation(controlName)" [required]="required" 
    [type]="type" [placeholder]="placeholder">
  @if(formGroup.get(controlName)?.invalid && formGroup.get(controlName)?.touched){
    <mat-error> {{ getErrorMessages(controlName) }} </mat-error>
  }
</mat-form-field>

在您的

getErrorMessages()
函数中,确保如果控件有错误则返回错误消息,或者如果没有错误则返回
''

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.