反应式表单验证问题

Reactive form validation issue

*ngIf 无法正常工作

我的表单包含无效字段;主要 if 条件运行良好,但当我显示特定错误消息时,它无法正常运行。 (示例:*ngIf="PopupForm.get('startdate').errors?.required

<div *ngIf="PopupForm.get('startdate').errors && submitted">
   <div class="form-text error" *ngIf="PopupForm.get('startdate').errors?.required">Start date is required</div>  
</div>

在您的 .ts 文件中创建 getter:

get getControls() {
    return this.PopupForm.controls;
}

.html

<div *ngIf="getControls.startdate.errors && submitted">
    <div *ngIf="getControls.startdate.touched && getControls.startdate.errors?.required">
       Start Date is required *
    </div> 
</div>

你试过这样做吗?

<div *ngIf="PopupForm.get('startdate')!.invalid && (PopupForm.get('startdate')!.dirty || PopupForm.get('startdate')!.touched)">
    <small class="form-text text-danger"
           *ngIf="PopupForm.get('startdate')?.errors?.required">
           This field is required.
    </small>
</div>