【问题标题】:access FormControl in FormGroup inside FormArray访问FormArray里面FormGroup中的FormControl
【发布时间】:2018-07-30 23:07:30
【问题描述】:

我正在尝试在 formarray 中的 formcontrol 上实现材料自动更正,但是当我尝试访问 ts 文件中的 formcontrol 时,它无法访问它。谁能帮帮我。

html 文件:

<div formArrayName="applicants">
          <div *ngFor="let applicant of appForm.controls.applicants.controls; let i=index; let last = last">
            <div [formGroupName]="i">
              <div class="row">
                <label for="applicant_short_name" class="col-sm-3 form-control-label">Applicant {{i+1}}</label>
                <div class="col-sm-7">
                  <div class="form-group">
                    <!-- <input type="text" formControlName="applicant_short_name" class="form-control" id="inputFirstName" placeholder="Applicant"> -->
                    <!-- <mat-form-field > -->
                      <input  type="text" class="form-control" id="inputFirstName" placeholder="Applicant" [matAutocomplete]="auto" [formControlName]="applicant_short_name">
                      <mat-autocomplete #auto="matAutocomplete">
                        <mat-option *ngFor="let state of filteredNames | async | slice:0:3" [value]="name">
                          <span>{{ name }}</span>
                        </mat-option>
                      </mat-autocomplete>
                    <!-- </mat-form-field> -->
                  </div>
                </div>

ts 文件:

    this.appForm.controls.applicants.controls[0].controls.applicant_short_name.valueChanges.subscribe(val => {
    this.filterNames(val);
 });

appform 是我的表单组 申请人是formarray 申请人简称为 formcontrol。

截至目前,controls[0] 正在抛出 AbstractControl 上不存在控件的错误。

谁能帮帮我?

提前致谢!

【问题讨论】:

  • 您是否在控制台上收到此错误?
  • 我无法自行编译。此错误来自编译。

标签: angular angular-material form-control


【解决方案1】:

你需要将你的对象类型定义为具体的类,而不是仅仅依赖于接口。我假设appForm 在您的代码中的某处被定义为FormGroupFormArray(您应该显示所有相关代码)。但是两个类的 controls 成员返回 AbstractControl[] 并且 AbstractControl 接口没有 controls 成员 - 它仅在 FormGroupFormArray 的类级别定义。所以,假设你使用FormGroups,你需要转换:

const outerGroup: FormGroup = this.appForm.controls.applicants as FormGroup;
const innerGroup: FormGroup = outerGroup.controls[0] as FormGroup;
innerGroup.controls.applicant_short_name.valueChanges.subscribe(val => {
    this.filterNames(val);
});

您也可以将语句内联,但这会变得非常混乱。

【讨论】:

    猜你喜欢
    • 2017-06-09
    • 2021-03-29
    • 2021-03-06
    • 2019-08-03
    • 2020-09-06
    • 2021-10-10
    • 2018-09-03
    • 1970-01-01
    • 2021-10-15
    相关资源
    最近更新 更多