0

我從數據庫中提取一些數據,並根據我想要創建表單的結果數量。例如。如果我得到總共3行的列名稱,年齡和班級。然後我需要創建三個表單元素,名稱,年齡和類作爲表單元素。在此先感謝在angular2中動態創建多個表單

回答

0

您可以使用FormArray創建多個表單組。

使用FormBuilder我們可以爲FormControls創建一個FormGroup。在FormGroup中,將一個變量定義爲FormArray,並將FormControls動態添加到該數組中。

public dataForm = FormGroup; 
const dbData = // data from database eg. [{name:x, age: 8, class: A},..] 
... 
constructor(
    private _fb: FormBuilder 
) {} 
... 
ngOnInit() { 
    this.dataForm = this._fb.group({ 
     subFormList: this._fb.array([]) 
    }); 
    this.getValues(); 
} 
getValues() { 
    const control = <FormArray> this.dataForm.get('subFormList'); 
    for (row of this.dbData) { 
     const temp = this._fb.group({ 
     name: [row['name']], 
     age: [row['age']], 
     class: [row['class']] 
     }); 
     control.push(temp); 
    } 
} 

希望這會對你有幫助。