【问题标题】:Form Control in form array is undefined表单数组中的表单控件未定义
【发布时间】:2019-07-15 01:24:59
【问题描述】:

我是 Angular 的新手,我对新添加的表单控件有问题。此表单控件在用户中不可见。 “结果”完美运行,但我新添加的“包含”在我执行

时会产生 UNDEFINED 结果
this.ATests.at(index).patchValue({include: 1});
alert(this.ATests.controls[index].value.include);

在我的 itsMine.component.ts 中。无论如何,这是执行此操作的复选框事件,请参阅下面的代码以获取更多详细信息。提前谢谢好人。


这是我的 itsMine.model.ts

export class ATbl {
    result: string;
    include: number;
  constructor (ATblForm){
      this.result=ATblForm.result || '';
      this.include=AtblForm.include || '';
  }
}

这是我的 itsMine.component.html

<form [formGroup]="AFormGroup">
    <div formArrayName="ATests" >
        <div fxlayout="row" fxLayoutAlign="center center" *ngFor="let test of ATests.controls; let i=index" [formGroupName]="i">
            <mat-checkbox [id]="'chkInclude_' + i"
                      (click)="setIncludeValue(i,$event)">
            </mat-checkbox>
        </div>
    </div>
</form>

这是我的 itsMine.component.ts

AFormGroup : FormGroup;

constructor(
    private fb: FormBuilder
){
    this.AFormGroup = this.fb.group({
        ATests: this.fb.array([])
    });
}

setIncludeValue(index,event) {
    this.ATests.at(index).patchValue({include: 1});
    alert(this.ATests.controls[index].value.include);
}

我错过了什么吗?非常感谢任何帮助。

【问题讨论】:

  • 你能在警报前做一个“console.log(this.ATests.controls[index].value)”吗?调用patchValue后的值是多少?我知道它应该是 {include: 1} 但由于某种原因它不是
  • 另一个提示以获得更多答案:您可以在 stackblitz.com 上提供一个示例,以便其他用户可以更快地找到您问题的解决方案
  • @TobiasGassmann 我做了 console.log(this.ATests.controls[index].value) 并且包含没有出现。嗯……

标签: angular angular-forms


【解决方案1】:

首先,您缺少ATests getter。您必须在您的FormArray 中推送FormGroupFormControl 的内容。然后你可以写类似

this.ATests.at(index).patchValue({include: 1});

alert中的说法也是错误的。

这是一个示例,说明如何使用FormArray 修补一些值并获取数据。

AFormGroup : FormGroup;

constructor(private fb: FormBuilder){
    this.AFormGroup = this.fb.group({
        ATests: this.fb.array([])
    });
    this.setIncludeControl();
    this.setIncludeValue(0,12);
}

get ATests() {
    return this.AFormGroup.get('ATests') as FormArray;
}

setIncludeControl() {
    this.ATests.push(
        this.fb.group({
            include: []
        })
    );
}

setIncludeValue(index, value) {
    this.ATests.at(index).patchValue({include: value});
    console.log(this.ATests.at(index).get('include').value);
}

Here你可以找到完整的演示。

【讨论】:

猜你喜欢
  • 2017-03-31
  • 2017-07-02
  • 1970-01-01
  • 2014-12-18
  • 1970-01-01
  • 2021-08-07
  • 2020-01-31
  • 2022-07-29
  • 2017-03-05
相关资源
最近更新 更多