【问题标题】:How can i get FormArray input values in parent element?如何在父元素中获取 FormArray 输入值?
【发布时间】:2022-01-06 17:47:16
【问题描述】:

如果 FormArray 在子组件中而我的主窗体在父组件中,我如何通过 FormArray 获取值(以反应方式)。我使用 FormGroups 的 FormGroupDirective 解决了这个问题,但这在 FormArrays 中不起作用(或者我不知道如何这是工作 :) )。我的目标是当我在输入中输入内容时,FormArray(product array) 中的内容是什么。它立即显示在我的主表单对象中。 这是一个 StackBlitz 链接 stackblitz

应用组件:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
  constructor(private formBuilder: FormBuilder) {}

  form: FormGroup;

  ngOnInit(): void {
    this.form = this.formBuilder.group({
      name: [''],
      sex: [''],
      infos: this.formBuilder.group({}),
      comments: this.formBuilder.array([]),
    });
  }
}

产品组件:

import { Component, OnInit } from '@angular/core';
import {
  FormArray,
  FormControl,
  FormGroup,
  FormGroupDirective,
} from '@angular/forms';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
})
export class ProductComponent implements OnInit {
  constructor(private formDirective: FormGroupDirective) {}

  productFormGroup: FormGroup;

  productForm: FormArray;

  ngOnInit(): void {
    this.handleFormGroup();
    this.productForm = this.formDirective.control.get('products') as FormArray;
  }

  handleFormGroup() {
    this.productFormGroup = new FormGroup({
      name: new FormControl(''),
      quantity: new FormControl(null),
      amountUnit: new FormControl(''),
    });
  }

}

产品html

<form class="myform" [formGroup]="productFormGroup">
  <mat-form-field >
    <mat-label>name</mat-label>
    <input matInput formControlName="name" />
  </mat-form-field>

  <mat-form-field >
    <mat-label>qua</mat-label>
    <input matInput formControlName="quantity" />
  </mat-form-field>

  <mat-form-field >
    <mat-label>amount</mat-label>
    <input matInput formControlName="amountUnit" />
  </mat-form-field>


</form>

【问题讨论】:

    标签: angular angular-reactive-forms formarray formgroups


    【解决方案1】:

    您可以订阅表单值更改并通过@output将其发送到父组件在此处修复它

    https://angular-ivy-jgju6y.stackblitz.io

    【讨论】:

    • 它可以正常工作,但这不是被动的方式。我确定 FormGroupDirective 有解决方案
    猜你喜欢
    • 1970-01-01
    • 2020-09-12
    • 2011-04-10
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多