Angular 2 - 如何在init上预填充3个表单组

时间:2017-03-20 20:16:43

标签: javascript angular typescript

我有以下代码,允许用户添加一组新字段。但我希望组件在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);
    }

}

1 个答案:

答案 0 :(得分:1)

您可以在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

        }));
}