【问题标题】:Angular 2: Accessing data from FormArrayAngular 2:从 FormArray 访问数据
【发布时间】:2017-03-31 12:48:00
【问题描述】:

我已经准备好使用 angular2/forms 提供的 ReactiveForms。这个表格有一个表格数组产品:

this.checkoutFormGroup = this.fb.group({
            selectedNominee: ['', Validators.required],
            selectedBank: ['', Validators.required],
            products: productFormGroupArray
        });

productFormGroupArray 是 FormGroup 对象的数组。我使用以下方法获取了控件,即 FormArray 对象:

this.checkoutFormGroup.get('products')

我正在尝试获取 products 数组中索引 i 处的元素。在不循环数组的情况下如何做到这一点?

编辑:

我尝试了可用的 at(index) 方法:

this.checkoutFormGroup.get('products').at(index)

但这会产生错误:

Property 'at' does not exist on type 'AbstractControl'.

编辑 2: 从服务器接收到 checkoutData 和 fund。

this.checkoutData.products.forEach(product => {
                    this.fundFormGroupArray.push(this.fb.group({
                        investmentAmount: [this.fund.minInvestment, Validators.required],
                        selectedSubOption: ['', Validators.required],
                    }))
            });

【问题讨论】:

  • 请分享您如何定义productFormGroupArray的代码
  • @ranakrunal9 编辑了问题

标签: angular typescript angular2-forms


【解决方案1】:

在组件内部:使用这个

(<FormArray>this.checkoutFormGroup.get('products')).at(index).get('yourFormControlName')

在 DOM 内部(在表单控件上应用验证)以这种方式使用它:

<form (ngSubmit)="onSubmit()" [formGroup]="checkoutFormGroup">
   
      <div>
        <h4 >Add Products Below</h4>
      
        <div  formArrayName="products">
          
          <div *ngFor="let subFormGroup of getControls(); let i = index">
            <div class="expense__input" [formGroupName]="i">
              <div class="input__group">
                <label for="Expense Type">Expense Type</label>
                <input type="text" 
                formControlName="productType">
                <span *ngIf="this.expenseForm.get('products').at(i).get('products').invalid">Product Type is Required</span>
              </div>
           </div>
        </div>
      </div>
   </div>

【讨论】:

    【解决方案2】:

    虽然在使用at() 方法之前将AbstractControl 转换为FormArray 是一种方法,但我没有看到有人指出您也可以使用get() 方法来实现它,该方法不需要转换。

    根据Angular's Documentationget()的签名是:
    get(path: string | (string | number)[]): AbstractControl | null

    这意味着您也可以使用它访问 FormArray 的控件。

    例子:

    const formGroup = new FormGroup({
      list: new FormArray([
        new FormControl('first'),
        new FormControl('second'),
      ]),
    });
    
    const firstValue = formGroup.get('list.0').value; // Returns 'first'
    const secondValue = formGroup.get('list.1').value; // Returns 'second'
    

    这真的很有用,当你想在 HTML 中绑定一个 FormControl 时,你不能转换任何东西:

    <input [formControl]="formGroup.get('list.0')">
    

    这里总结了一些方法:

    const firstControl = listControl.get('list.0');
    
    const firstControl = listControl.get(['list', 0]);
    
    const firstControl = listControl.get('list').get('0'); // You need a string and not a number
    
    const listControl = formGroup.get('list') as FormArray;
    const firstControl = listControl.at(0);
    

    【讨论】:

    • 太好了,谢谢您的回答。 get('list.0') 而不是更直观的get('list[0]') 将成为许多开发人员的一大难题。
    【解决方案3】:

    一个衬线作为当前接受答案的一个选项

    var item = (<FormArray>this.checkoutFormGroup.get('products')).at(index);
    

    【讨论】:

    • 旧语法改用 as
    【解决方案4】:

    //在.ts组件文件中//

    getName(i) {
        return this.getControls()[i].value.name;
      }
    
      getControls() {
        return (<FormArray>this.categoryForm.get('categories')).controls;
      }
    

    // 反应形式 - 模板文件 //

    <mat-tab-group formArrayName="categories" class="uk-width-2-3" [selectedIndex]="getControls().length">
          <mat-tab
            *ngFor="let categoryCtrl of getControls(); let i = index"
            [formGroupName]="i"
            [label]="getName(i)? getName(i) : 'جديد'"
          >
    </mat-tab>
    </mat-tab-group>
    

    【讨论】:

      【解决方案5】:

      只需将该控件转换为数组

      var arrayControl = this.checkoutFormGroup.get('products') as FormArray;
      

      它的所有功能都在那里

      var item = arrayControl.at(index);
      

      【讨论】:

      • 返回未定义
      猜你喜欢
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-03-06
      • 2018-08-29
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多