簡體   English   中英

Angular 8:如何將 formControlName 與 FormArray 一起使用

[英]Angular 8: How to use formControlName with FormArray

如何將 map formControlName設置為特定的formArray項?

我無法控制服務器數據並嘗試使用電話號碼數組創建表單。

表單本身在視覺上不會並排布置電話,我希望能夠像通常使用 formGroup 一樣聲明電話的輸入控件。

到目前為止,我所擁有的是以下內容:

Controller:

const exampleData = {
                'name': 'John Doe',
                'phones': [
                    {
                        'type': 'home',
                        'number': '5555555'
                    },
                    {
                        'type': 'cell',
                        'number': '5555555'
                    }
                ]
            };

    this.form = this.fb.group({
         name:[],
         phones: this.fb.array([
             this.fb.group({
                 type: '',
                 number: []
             }),
             this.fb.group({
                 type: '',
                 number: []
             })
         ]),
     });

    this.form.patchValue(exampleData);

模板

<input type="text" formControlName="name">

<!--  This works but I need to loop -->
<div formArrayName="phones">
    <div *ngFor="let phone of form.get('phones').controls; let i = index">
        <div [formGroupName]="i">
            <label>Type: </label><input formControlName="type"/>
            <label>Number: </label><input formControlName="number"/>
        </div>
    </div>
</div>

<!--  How can I point to a phone directly? -->
<input type="text" formControlName="point to type home's number...with helper function or something...">

看看這是否可能?

我通過再次對那個組件運行setValue來解決這個問題,這就是為什么同一個表單控件的任何輸入都會更新,當我們使用 ngModel 時,這就像兩種方式的數據綁定,其中數據流向即時和其他控件。

這個方法將創建formGroup

getPhoneGroup() {
    const form = this.fb.group({
      type: '',
      num: []
    });

    const elm = form.get('num');
    elm.valueChanges.subscribe(val => {
      elm.setValue(val, { emitEvent: false })
    });

    return form;
  }

演示

試試這個來訪問 formArray 項目:

  <div [formGroup]="form.get('phones').at(1)">
    <input type="text" formControlName="num">
  </div>

堆棧閃電戰

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM