微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何使用 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);
 }

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。