嵌套反应式数组问题(Angular 7)

时间:2019-03-01 16:50:24

标签: angular forms angular-reactive-forms

我有一个Angular 7应用,我试图在其中添加一个反应式表单,该表单在多个类别标题下填充一组控件。我很喜欢处理HTML方面的内容。

除“来源”组的人口外,大多数工作。我已验证itemArray正确填充。但是,一旦将其合并到最终的sourceForm中,则Sources / controls下的控件将没有任何值。我确定在将数组传回时我的逻辑或类型有问题,但是在尝试解决数天之后,我无法确定问题出在哪里。代码如下。有人可以帮我解决我在这里做错的事情吗?

import {Component, OnInit} from '@angular/core';
import {environment as env} from '../../environments/environment';
import {OARDataService} from '../oar-data.service';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {FormBuilder, FormGroup, FormControl, FormArray} from '@angular/forms';
import {scSource} from './scSource-model';
import {scSourceCategory} from './scSourceCategory-model';


@Component({
    selector: 'app-sc-client-sources',
    templateUrl: './sc-client-sources.component.html',
    styleUrls: ['./sc-client-sources.component.css']
})
export class ScClientSourcesComponent implements OnInit {

    sourceForm: FormGroup;
    source$: scSource[];
    cat$: scSourceCategory[];

    constructor(private _oardata: OARDataService, private _fb: FormBuilder) {
    }

    ngOnInit() {
        this._oardata.getscCategories().subscribe(data => {
            this.cat$ = data;
            this.createForm(this.cat$);
            console.log(this.sourceForm);
        });
    }

    public createForm(cat$: any) {
        var catArray = [];

        for (var c = 0; c < cat$.length; c++) {
            var selectedCat = this.cat$[c].scSourceCategoryID

            //catArray.push(this.buildCategoryHeader(cat$[c]))
            catArray.push(this._fb.group({
                CategoryID: this.cat$[c].scSourceCategoryID,
                Category: this.cat$[c].scSourceCategoryName,
                Sources: this._fb.array([this.getSourcesForCategory(selectedCat)])
            }));

            this.sourceForm = this._fb.group(catArray);
        }
        return this.sourceForm;
    }

    buildSource(sourceInstance: any): FormGroup {

        return this._fb.group({
            sourceID: [sourceInstance.scClientSourceID],
            sourceName: [sourceInstance.scSourceName]
        });
    }

    getSourcesForCategory(selectedCat: number): FormGroup {

        var itemArray = [];

        this._oardata.getscSources(selectedCat).subscribe(data => {
            this.source$ = data;
            for (var i = 0; i < this.source$.length; i++) {
                itemArray.push(this.buildSource(this.source$[i]));
            }
        });
        console.log(itemArray);
        return this._fb.group(itemArray);
    }
}

图像代表我在控制台中看到的值。 itemArray:

The ItemArry values when not inserted into the form

然后sourceForm值:

The sourceForm Values. Notice the NULL value under Sources

0 个答案:

没有答案