【问题标题】:Getting values out of Angular form group从 Angular 表单组中获取值
【发布时间】:2020-12-09 04:12:37
【问题描述】:

我是 Angular 的新手,我正在尝试创建一个动态表,您可以在其中添加新的列、行和数据。我遇到的问题是从表单组中获取输入数据并将其推送到表正在读取的对象中。

初始组如下所示,每个控件显示为一列。

input = new FormGroup({
   name: new FormControl(),
   age: new FormControl(),
   height: new FormConrol()
});

因此,当您添加一列时,会使用“input.addControl()”添加一个新控件。

无需添加任何新列,我可以轻松地将其推送到数据源,但要说,

this.dataSource.push({name: this.input.value.name}) // and so forth

但是当添加新列时,我不知道如何将值推送到这个 dataSource 变量,因为它们可以被称为任何东西。

有没有办法说迭代表单组值并像这样或类似的方式推动它们......任何帮助将不胜感激。

【问题讨论】:

  • 是的,你会将 formGroup 推送到 formArray 上

标签: angular angular-forms formgroups


【解决方案1】:

您真正需要的是FormArray 而不是FormGroup。 FormArray 更像Array。您可以push 值并从中删除值

在下面的示例中,我正在实现 FormBuilder 以生成 FormGroup 和 FormArray

export class AppComponent {
 
  addInput({ name, age, height }: IFormItem = {}) {
    this.inputs.push(
      this.fb.group({
        name: [name, []],
        age: [age, []],
        height: [height, []]
      })
    );
  }
  removeInput(i: number) {
    this.inputs.removeAt(i);
    this.inputs.updateValueAndValidity();
    this.myForm.updateValueAndValidity();
  }
  myForm = this.fb.group({
    inputs: this.fb.array([])
  });

  get inputs() {
    return this.myForm.get("inputs") as FormArray;
  }
  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.addInput({
      name: 'Test Name',
      age: 5,
      height: 45
    });
    this.addInput();
  }
}

在 HTML 中

<form [formGroup]='myForm'>
  <button (click)='addInput()'>Add</button>
  <table formArrayName='inputs'>
    <tr>
      <th>#</th>
      <th>Name</th>
      <th>Age</th>
      <th>Height</th>
    </tr>
    <tr *ngFor="let input of inputs.controls; let i = index" [formGroupName]='i'>
      <td>{{ i + 1}}</td>
      <td><input formControlName='name'></td>
      <td><input formControlName='age'></td>
      <td><input formControlName='height'></td>
      <td><button (click)='removeInput(i)'>Delete</button></td>
    </tr>
 </table>
</form>

See this stackblitz demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 2017-09-07
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多