Angular 使用 ngif 进行表单验证

Angular Form Verification with ngif

获得了一个带有用户名字文本框的表单。正在尝试添加一些验证。

使用简单形式时 -- 像这样的单个错误行就可以正常工作

<div class="col-12 col-md-6">
            <input type="text" name="firstName" placeholder="* name" required [(ngModel)]="contact.firstName" class="form-control" minlength="2" pattern="[a-zA-Z ]*" #firstName="ngModel" [class.is-invalid]="firstName.invalid && firstName.touched" />
            <small [class.d-none]="firstName.valid || firstName.untouched" class="error-msg">* field is required & must have two or more letters from the abc</small>
</div>

当尝试分离错误并仅显示相关错误时,使用 *ngif 会导致在输入字段上强制进行验证, 错误消息未显示。

<div class="col-12 col-md-6">
            <input type="text" name="firstName" placeholder="* name" required [(ngModel)]="contact.firstName" class="form-control" minlength="2" pattern="[a-zA-Z ]*" #firstName="ngModel" [class.is-invalid]="firstName.invalid && firstName.touched" />
            
            <div *ngif="firstName.errors && (firstName.invalid || firstName.touched)">
                <small class="error-msg" *ngif="firstName.errors.required">* is required</small>
                <small class="error-msg" *ngif="firstName.errors.pattern">* enter only letters</small>
                <small class="error-msg" *ngif="firstName.errors.minlength">* must have at least 2 letters</small>
            </div>
        </div>

不确定是什么问题

我认为 *ngif 打错了,您应该将其更改为 *ngIf(驼峰式)。