我有下面的代码,它允许用户添加一组新的字段。但是我希望组件在init上渲染3组数据。
目前,通过initRateRow函数创建了一组字段,但是如何使它通过httpservice循环以将其推入“ this._fb.group”?
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-exchange-rates',
templateUrl: './exchange-rates.component.html',
styleUrls: ['./exchange-rates.component.scss']
})
export class ExchangeRatesComponent implements OnInit {
public myForm: FormGroup;
constructor(private _fb: FormBuilder) { }
ngOnInit() {
this.myForm = this._fb.group({
rates: this._fb.array([
this.initRateRow(),
])
});
}
initRateRow() {
return this._fb.group({
rateUnit: ['24', Validators.required],
currencyFrom: ['GBP', Validators.required],
currencyTo: ['USD', Validators.required]
});
}
blankRateRow() {
return this._fb.group({
rateUnit: ['', Validators.required],
currencyFrom: ['', Validators.required],
currencyTo: ['', Validators.required]
});
}
addRateRow() {
const control = <FormArray>this.myForm.controls['rates'];
control.push(this.blankRateRow());
}
removeRateRow(i: number) {
const control = <FormArray>this.myForm.controls['rates'];
control.removeAt(i);
}
save(model) {
// call API to save
// ...
console.log(model);
}
}
最佳答案
您可以在ngOnInit()
中进行。
ngOnInit(){
let url = '/getData'; // API url
this.http.get(url)
// Assuming data arrive as json
.map(r => r.json())
// Assuming data arrive as array of row
.subscribe(rowArray => rowArray.forEach(row => {
// Use `row` to init 1 row
}));
}
关于javascript - Angular 2-如何在init上预填充3个表单组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42913170/