首页 > 解决方案 > 如何为多选控件动态添加[formcontrol]?

问题描述

我正在使用 Angular 9 中的反应式表单。我需要动态生成表单,表单可能包含许多控件,其他控件工作正常,但我遇到了multi-select.

多选的html代码是:

<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>

我需要在运行时动态添加[formControl]in<mat-select>和 at <ngx-mat-select-search>,这样如果表单包含多个多选字段,它就会很好地工作。

我的代码工作正常,可以在单独的多选中加载数据,很好地保存选择列表。但是显示所选列表会导致问题,[formControl]因为它不是动态添加的。

我已经尝试通过在对象中添加 formControl 作为“选项”属性:

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('')
  }));
}

但这东西行不通。我需要在运行时添加 formControl 时找出问题,还是有其他方法?

标签: angularangular-materialmulti-select

解决方案


推荐阅读