【问题标题】:Accessing form Array values to display Mat Error访问表单数组值以显示 Mat Error
【发布时间】:2020-01-27 17:57:11
【问题描述】:

表单组

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

【问题讨论】:

    标签: angular angular-reactive-forms formarray


    【解决方案1】:

    感谢您的尝试,我找到了以下代码的解决方案:

    <mat-error *ngIf="workTiming.controls[pointIndex].get('beginTime').hasError('required')"> Enter begin time </mat-error>
    

    【讨论】:

      【解决方案2】:

      您正在尝试直接访问不适用于外部上下文的嵌套表单。通过父表单访问嵌套表单,就像访问 JS 对象元素一样:

      <mat-error *ngIf="locationForm.get('workTiming.beginTime').hasError('required')"> 
        Enter begin time 
      </mat-error>
      

      【讨论】:

      • 谢谢,但上面的答案没有按预期工作。它使用以下代码: Enter begin time
      【解决方案3】:

      可以写成

      <mat-error *ngIf="item.get('beginTime').errors?.required"> Enter begin time </mat-error>
      

      【讨论】:

        猜你喜欢
        • 2020-01-31
        • 1970-01-01
        • 2021-12-18
        • 1970-01-01
        • 2018-07-29
        • 2018-03-26
        • 2010-12-11
        • 2021-02-25
        • 1970-01-01
        相关资源
        最近更新 更多