'Dynamic Angular Forms on User Interaction

I have a dropdown that the user uses to switch between different Angular forms.

HTML

<form [formGroup]="evalForm">
    <mat-form-field appearance="fill">
        <mat-label>Select Analysis Group</mat-label>
            <mat-select (selectionChange)="groupSelected($event)">
                    <mat-option *ngFor="let item of groupDropdown | async" [value]="item.value">{{item.text}}</mat-option>
            </mat-select>
    </mat-form-field>

    <ng-container *ngFor="let groups of groupSections;">
        <input type="text" [formControlName]="groups?.name">
    </ng-container>
</form>

What should the Angular look like to get the reactive forms working when someone selects an item in the dropdown?

What groupSelected() currently does (basic non-working pseudo-code):

groupSelected(selectedItem) {

    // 1) Grabs the FormControlNames from the DB
    const formControlNamesList = getItemsFromDB(selectedItem);

    // 2) Sets FormControlNames for DOM
    // [{groups:{name: 'keyOne'}}, {groups:{name: 'keyTwo'}},{groups:{name: 'keyThree'}}]
    this.groupSections = setGroupSections(formControlNamesList);

    // 3) Creates a formControlNamesList Object in the form
    // {"keyOne": FormControl, "keyTwo": FormControl, "keyThree": FormControl}
    const formObj = formatForAngularForms(formControlNamesList);

    // 4) Set the Reactive Form
    this.evalForm = this.fb.group(new FormGroup(formObj));

}

formatForAngularForms(formControlNamesList) {
    const formObj = {};
    for(let i=0;i<formControlNamesList.length;i++) {
        formObj[formControlNamesList[i].name] = new FormControl(null,[Validators.required]);
    }
    return formObj;
}

At the moment, the console explodes with errors about how it can't find the FormControlName and I suspect it has to do with the timing of when everything gets rendered, but I'm not entirely sure if that's it or not. I need the forms to render completely new forms each time a new value selected from the dropdown. The UI will always be dynamic and each time the dropdown changes the input FormControlNames could be different based on what the DB sends.

I've read that maybe FormArray might be something use but I can't find an example anywhere that matches what I'm looking to do.



Solution 1:[1]

Shouldn't you wait for the answers from backend before proceeding to build the form? If getItemsFromDB() returns an observable you could do async/await:

async groupSelected(selectedItem) {
    const formControlNamesList = await getItemsFromDB(selectedItem);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1