VansFannel
VansFannel

Reputation: 45921

Don't show FormArray if it is empty or undefined in a Reactive Form

I've just started to learn Angular 4 doing my first project.

I have created a Reactive Form to show a form with the following structure:

Form (FormGroup)
  |
  --> aggLevels (FormArray)
       |
       --> aggregationLevelName (FormControl? I show it in a label)
       |
       --> variableDataForLevel (FormArray)
            |
            --> variableDataId (FormControl)
            |
            --> value (FormControl)

This is the component HTML:

<form [formGroup]="varDataForm" (ngSubmit)="onSubmit()" novalidate>
    <div formArrayName="aggLevels"
         *ngFor="let agLevel of varDataForm.get('aggLevels')?.controls; let aggLevelId = index;">
        <div [formGroupName]="aggLevelId">
            <label>{{agLevel?.get('aggregationLevelName')?.value}}</label>
            <div formArrayName="variableDataForLevel"
                 *ngFor="let vardata of varDataForm.get('aggLevels')?.controls[0]?.get('variableDataForLevel')?.controls; let rowIndex = index;">
                <div [formGroupName]="rowIndex">
                    <select formControlName="variableDataId">
                        <option *ngFor="let gs1 of gs1AIs" [value]="gs1.Id">{{gs1.description}}</option>
                    </select>
                    <input formControlName="value" placeholder="Valor">
                    <div class="error" *ngIf="vardata.get('value').hasError('required') && vardata.get('value').touched">
                        Obligatorio
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

My problem here is when there isn't any element in variableDataForLevel FormArray. I get this message:

ng:///AppModuleShared/VarDataComponent.ngfactory.js:49 ERROR Error: Cannot find control with path: 'aggLevels -> 1 -> variableDataForLevel -> 0'

I have tried to add safe navigation operator ? at the end of all elements:

varDataForm.get('aggLevels')?.controls[0]?.get('variableDataForLevel')?.controls

But I still get the problem. FormArray aggLevels and variableDataForLevel aren't undefined because when I create it I instance it.

What can I do to don't show the FormArray if is empty?

I new with Angular and I have few knowledge about how to fix it.

This is the component typescript class for this component:

import { Component, Inject } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl, Validators } from '@angular/forms';
import { Http, RequestOptions, Headers } from '@angular/http';
import { IProductionOrder } from '../../interfaces/productionorder.interface';
import { IAggLevel } from '../../interfaces/aglevel.interface';
import { IGS1 } from '../../interfaces/gs1.interface';
import { IVarData } from '../../interfaces/vardata.interface';

@Component({
    selector: 'vardata',
    templateUrl: './vardata.component.html'
})

export class VarDataComponent {
    public productionorders: IProductionOrder[];
    public gs1AIs: IGS1[];

    public varDataForm: FormGroup = new FormGroup({});
    public selectedProductionOrder: string;

    constructor(private http: Http,
        @Inject('BASE_URL') private baseUrl: string,
        @Inject(FormBuilder) private fb: FormBuilder) {

        this.selectedProductionOrder = '';

        http.get(baseUrl + 'api/ProductionOrder/0').subscribe(result => {
            this.productionorders = result.json() as IProductionOrder[];

            console.log(this.productionorders);
        }, error => console.error(error));
    }

    productionOrderChanges() {
        if (this.selectedProductionOrder != '') {
            let urlVarData: string = this.baseUrl + 'api/VariableData/' + this.selectedProductionOrder;
            let urlAggLevel: string = this.baseUrl + 'api/AggregationLevelConfiguration/' + this.selectedProductionOrder;

            this.http.get(urlAggLevel).subscribe(result => {
                let aggLevels: IAggLevel[] = result.json() as IAggLevel[];

                console.log('niveles');
                console.log(aggLevels);

                if ((aggLevels != null) && (aggLevels.length > 0)) {

                    this.http.get(urlVarData).subscribe(result => {
                        let varDatas: IVarData[] = result.json() as IVarData[];

                        console.log('variable data');
                        console.log(varDatas);

                        this.varDataForm = this.fb.group({
                            aggLevels: this.fb.array(this.createForm(aggLevels, varDatas))
                        });

                    }, error => console.error(error));
                }

            }, error => console.error(error));
        }
        else
            this.varDataForm = new FormGroup({});
    }

    createForm(aggLevels: IAggLevel[], varDatas: IVarData[]): any[] {
        let array: any[] = [];

        for (let level of aggLevels) {
            let group: FormGroup;
            let varDataForLevel: IVarData[] =
                varDatas.filter(v => v.aggregationLevelConfigurationId == level.aggregationLevelConfigurationId);

            group = this.createFormGroupForLevel(level, varDataForLevel);
            array.push(group);
        }

        return array;
    }

    createFormGroupForLevel(level: IAggLevel, varDatas: IVarData[]): FormGroup {
        let group: FormGroup;

        group = this.fb.group({
            aggregationLevelName: level.name,
            variableDataForLevel: this.fb.array(this.createVarDataControls(varDatas))
        });

        return group;
    }

    createVarDataControls(varData: IVarData[]): any[] {
        let array: any[] = [];

        for (let vData of varData) {
            let group: FormGroup;

            group = this.fb.group({
                variableDataId: vData.variableDataId,
                value: vData.value
            });

            array.push(group);
        }

        return array;
    }



    disableSubmit() {
        return (!this.varDataForm.valid);
    }

    onSubmit() {
    }
}

I think the problem is here:

createVarDataControls(varData: IVarData[]): any[] {
    let array: any[] = [];

    for (let vData of varData) {
        let group: FormGroup;

        group = this.fb.group({
            variableDataId: vData.variableDataId,
            value: vData.value
        });

        array.push(group);
    }

    return array;
}

if varData is empty it will return a Any[], but I don't think return this is an error because I don't want to show something empty on the form.

I have edited method createVarDataControls to return a FormGroup if varData is empty. This let me continue but I don't think it answers my question:

createVarDataControls(varData: IVarData[]): any[] {
    let array: any[] = [];

    if ((varData == null) || (varData.length == 0)) {
        let group: FormGroup;

        group = this.fb.group({
            variableDataId: '',
            value: ''
        });

        array.push(group);
    }
    else {
        for (let vData of varData) {
            let group: FormGroup;

            group = this.fb.group({
                variableDataId: vData.variableDataId,
                value: vData.value
            });

            array.push(group);
        }
    }

    return array;
}

With it I don't get any exception but it shows two empty controls, and I don't want that. This is only useful to identify the problem.

Upvotes: 3

Views: 6996

Answers (1)

VansFannel
VansFannel

Reputation: 45921

I have found the problem. I would like my solution if it can helps someone.

In the second FormArray loop:

<div formArrayName="variableDataForLevel"
                 *ngFor="let vardata of varDataForm.get('aggLevels')?.controls[0]?.get('variableDataForLevel')?.controls; let rowIndex = index;">

But the correct one is:

<div formArrayName="variableDataForLevel"
        *ngFor="let vardata of agLevel.get('variableDataForLevel')?.controls; let rowIndex = index;">

I have changed varDataForm.get('aggLevels')?.controls[0]? with agLevel.

And also I have changed the method createVarDataControls to return undefined when there aren't variable data to show on it:

createVarDataControls(varData: IVarData[]): any[] | undefined {
    let array: any[] = [];

    if ((varData == null) || (varData.length == 0)) {
        return undefined;
    }
    else {
        for (let vData of varData) {
            let group: FormGroup;

            group = this.fb.group({
                aggregationLevelConfigurationId: vData.aggregationLevelConfigurationId,
                productionOrderId: vData.productionOrderId,
                variableDataId: vData.variableDataId,
                value: vData.value
            });

            array.push(group);
        }

        return array;
    }
}

Try and failure until find the solution!

Upvotes: 1

Related Questions