访问表单数组值以显示垫错误
Accessing form Array values to display Mat Error
表格组
this.locationForm = this.formBuilder.group({
locationName: new FormControl(null, Validators.required),
locationURL: new FormControl(null, Validators.required),
workTiming: this.formBuilder.array([
this.formBuilder.group({
beginTime: new FormControl(null,Validators.required),
})
])
})
HTML 代码:
<div formArrayName="workTiming" >
<div *ngFor="let item of workTiming.controls;
let pointIndex=index" [formGroupName]="pointIndex">
<div class="container">
<mat-form-field class="responsive">
<input type="time" required formControlName="beginTime" matInput placeholder="Begin Time">
<mat-error *ngIf="workTiming.get('beginTime').hasError('required')"> Enter begin time </mat-error>
</mat-form-field>
</div>
</div>
</div>
我需要一些关于如何在 mat-error 中访问 'beginTime' 的 formControl 名称的帮助,因为我使用的是 formArray,所以我不确定如何访问它。如果我在代码中给出 like 我会得到如下错误
ERROR TypeError: Cannot read property 'hasError' of null
您正在尝试直接访问嵌套表单,该表单不可用于外部上下文。通过父表单访问嵌套表单就像访问 JS 对象元素一样:
<mat-error *ngIf="locationForm.get('workTiming.beginTime').hasError('required')">
Enter begin time
</mat-error>
感谢您的尝试,我找到了以下代码的解决方案:
<mat-error *ngIf="workTiming.controls[pointIndex].get('beginTime').hasError('required')"> Enter begin time </mat-error>
可以写成
<mat-error *ngIf="item.get('beginTime').errors?.required"> Enter begin time </mat-error>
表格组
this.locationForm = this.formBuilder.group({
locationName: new FormControl(null, Validators.required),
locationURL: new FormControl(null, Validators.required),
workTiming: this.formBuilder.array([
this.formBuilder.group({
beginTime: new FormControl(null,Validators.required),
})
])
})
HTML 代码:
<div formArrayName="workTiming" >
<div *ngFor="let item of workTiming.controls;
let pointIndex=index" [formGroupName]="pointIndex">
<div class="container">
<mat-form-field class="responsive">
<input type="time" required formControlName="beginTime" matInput placeholder="Begin Time">
<mat-error *ngIf="workTiming.get('beginTime').hasError('required')"> Enter begin time </mat-error>
</mat-form-field>
</div>
</div>
</div>
我需要一些关于如何在 mat-error 中访问 'beginTime' 的 formControl 名称的帮助,因为我使用的是 formArray,所以我不确定如何访问它。如果我在代码中给出 like 我会得到如下错误
ERROR TypeError: Cannot read property 'hasError' of null
您正在尝试直接访问嵌套表单,该表单不可用于外部上下文。通过父表单访问嵌套表单就像访问 JS 对象元素一样:
<mat-error *ngIf="locationForm.get('workTiming.beginTime').hasError('required')">
Enter begin time
</mat-error>
感谢您的尝试,我找到了以下代码的解决方案:
<mat-error *ngIf="workTiming.controls[pointIndex].get('beginTime').hasError('required')"> Enter begin time </mat-error>
可以写成
<mat-error *ngIf="item.get('beginTime').errors?.required"> Enter begin time </mat-error>