我创建了一个通用组件。我陷入了一个问题,我正在使用有角度的材料并使用垫子形式场。我在 Angular 18 中使用 @if 来检查条件,然后 mat-error 工作正常。但是当我使用 @for 时它不起作用并且 mat-error 显示在输入字段内而不是 mat-error 中。我还需要这样写我的条件:
以上是我正在寻找的所需格式。但我也尝试使用单个@if和@for。但@for 不起作用。 这是我使用 @for 时的输出:
@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 寻找以下输出:
预期输出,目前我只使用了@if,所以我得到了这个输出
我不知道你为什么要@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()
函数中,确保如果控件有错误则返回错误消息,或者如果没有错误则返回 ''
。