How to add [formcontrol] dynamically for multi select control?

Viewed 295

I am working on reactive form in Angular 9. I need to generate the form dynamically, form may contain many controls, other controls are working fine, but I am getting the issue with multi-select.

The html code for multiselect is:

<mat-form-field appearance="outline" *ngIf="obj.fieldType == 'multi-select-list'">
<mat-label>{{obj.fieldName}}:</mat-label>
<mat-select required #regionMultiSelect
            [formControl]="obj.options"
            name="{{obj.fieldName}}" [multiple]="true"
            (closed)="getRegionList(obj)">
    <mat-select-trigger
    [innerHTML]="this.multiSelectMapDisplayStr.get(obj.fieldName)"></mat-select-trigger>
    <ngx-mat-select-search [showToggleAllCheckbox]="true"
                            (toggleAll)="toggleSelectRegions($event,obj)"
                            [formControl]="regionFilterCtrl"
                            placeholderLabel="Search"
                            noEntriesFoundLabel="'No matches found'"></ngx-mat-select-search>
    <mat-option
    *ngFor="let region of obj.dataSet"
    [value]="region">
    {{region}}
    </mat-option>
</mat-select>
</mat-form-field>

I need [formControl] in <mat-select> and at <ngx-mat-select-search> to be added dynamically at runtime, so that it will work well if a form contains multiple multi-selects fields.

My code working fine to load the data in separate multi-select, saving the select list fine. But displaying the selected list causing issue due to [formControl] as it is not dynamically added.

I have tried by adding formControl in the object as in 'options' attribute:

if (value.fieldType === 'single-select-list' || 'multi-select-list') {
  this.objectFields.push(this._formBuilder.group({
    fieldLabel: [value.fieldLabel, Validators.required],
    fieldType: [value.fieldType, Validators.required],
    fieldName: [value.fieldName],
    dataSet: [value.dataSet],
    required: [value.required],
    displayInGrid: [value.displayInGrid],
    options: new FormControl('')
  }));
}

But this thing is not working. I need to figure out the issue while adding the formControl at run-time or is there any other way?

0 Answers
Related