FormGroup
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,所以我不确定如何访问它。如果我在代码中给出类似的代码,则会出现如下错误
ERROR TypeError: Cannot read property 'hasError' of null
答案 0 :(得分:0)
您正在尝试直接访问嵌套表单,该表单不适用于外部上下文。通过父表单访问嵌套表单,就像访问JS对象元素一样:
<mat-error *ngIf="locationForm.get('workTiming.beginTime').hasError('required')">
Enter begin time
</mat-error>
答案 1 :(得分:0)
感谢尝试,我找到了以下代码的解决方案:
<mat-error *ngIf="workTiming.controls[pointIndex].get('beginTime').hasError('required')"> Enter begin time </mat-error>
答案 2 :(得分:0)
可以写为
<mat-error *ngIf="item.get('beginTime').errors?.required"> Enter begin time </mat-error>