如何使用 Angular 中多个动态下拉列表中的选定值填充数组?

问题描述

我正在尝试使用从另一个数组动态生成的多个下拉列表中的所有选定值填充字符串数组。 (exp:我有一个locations:string[n],我想构建n个下拉列表,每个下拉列表都包含所有位置值,我可以从下拉列表中选择一些值来构建我的数组)。

IMAGE

这里是我的 HTML

const { username } = useParams();

useEffect(()=>{
console.log(username)},[username]);

这里是我的表单声明:

<div fxLayout="row wrap" gdColumns="repeat(auto-fit,minmax(240px,1fr))" gdGap="10px"
                         class="zone-code-label" *ngFor="let _ of locations; index as index"
                         formArrayName="locationForm">
                        <mat-form-field appearance="outline" *ngFor="let _ of locationForm.controls; index as i">
                            <mat-label>{{'ASSET_CATALOG.FORM.FIELDS.LOCATION'| translate}}{{' '}}{{index + 1}}</mat-label>
                            <mat-select [formGroupName]="i"
                                        [placeholder]="'ASSET_CATALOG.FORM.FIELDS.LOCATION' | translate">
                                <mat-option>
                                    <ngx-mat-select-search formControlName="location"
                                                           [placeholderLabel]="'ASSET_CATALOG.FORM.CONfig_LOCATION_SEARCH' | translate"
                                                           [noEntriesFoundLabel]="'ASSET_CATALOG.FORM.CONfig_LOCATION_EMPTY' | translate"
                                    ></ngx-mat-select-search>
                                </mat-option>
                                <mat-option *ngFor="let item of filteredLocationList| async"
                                            [value]="!!item? item.code: ''">
                                    <span> {{item.code + ' - ' + item.label}}</span>
                                </mat-option>
                            </mat-select>
                        </mat-form-field>
                    </div>

正如您在此处看到的,提交后我的数组通常为空,并且未采用选定的值。

result

问题在于 formcontrol 和 FormArray。

请帮忙!

谢谢。

解决方法

你可以使用 (selectionChange) 函数来触发一个事件,在那里你可以做任何你想做的事情,包括推送到一个数组。这也适用于多个标签。

第一个垫子选择....

<mat-select (selectionChange)="addItem($event.value)" multiple>
 <mat-option *ngFor="let item of items" [value]="item.value">
 {{item.value}}
  </mat-option>
  </mat-select>

第二个垫子选择....

 <mat-select (selectionChange)="addItem($event.value)" >
        <mat-option *ngFor="let s of something" [value]="s.value">
          {{s.value}}
        </mat-option>
      </mat-select>

打字稿

ngOnInit(): void {
this.selectedItems=[];
}

 addItem(item:any){
   this.selectedItems.push(item);
 }

不用说,您还必须处理未选择的项目,但这取决于您想出如何将其删除。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...