Как я могу заполнить массив выбранными значениями из нескольких динамических выпадающих списков в Angular?

#angular #angular-material #formarray

#angular #angular-материал #формаррей

Вопрос:

Я пытаюсь заполнить массив строк всеми выбранными значениями из моего множественного выпадающего списка, динамически генерируемого из другого массива. (пример: у меня есть locations: string[n], и я хочу создать n выпадающих списков, каждый из которых содержит все значения locations, и я могу выбрать некоторые значения из своего выпадающего списка для построения своего массива).

ИЗОБРАЖЕНИЕ

Здесь мой HTML

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

И вот мое объявление Forms:

 InitAssetCatalogForm(): void {
    this.assetCatalogForm.form = new FormGroup({
        code: new FormControl(null, [Validators.required]),
        label: new FormControl(null, [Validators.required]),
        price: new FormControl(null, [Validators.required]),
        measureUnit: new FormControl(null),
        supplier: new FormControl(''),
        ean: new FormControl(null, [Validators.required]),
        createdBy: new FormControl(null),
        createDate: new FormControl(null),
        nomenclature: new FormControl(null),
        duration: new FormControl(null),
        shelfLifeUnit: new FormControl(null),
        conditioning: new FormControl(null),
        weight: new FormControl(null),
        volume: new FormControl(null),
        minimumStock: new FormControl(null),
        height: new FormControl(null),
        length: new FormControl(null),
        width: new FormControl(null),
        ray: new FormControl(null),
        subRay: new FormControl(null),
        type: new FormControl(null),
        subType: new FormControl(null),
        segment: new FormControl(null),
        supplierCodeCtrl: new FormControl(null),
        conditioningCodeCtrl: new FormControl(null),
        measureUnitCodeCtrl: new FormControl(null),
        nomenclatureRayCodeCtrl: new FormControl(null),
        nomenclatureSubRayCodeCtrl: new FormControl(null),
        nomenclatureTypeCodeCtrl: new FormControl(null),
        nomenclatureSubTypeCodeCtrl: new FormControl(null),
        nomenclatureSegmentCodeCtrl: new FormControl(null),
        locationForm: new FormArray([
            new FormGroup({
                location: new FormControl(null)
            })
        ])
    });
 

Как вы можете видеть здесь, мой массив обычно пуст после отправки, и выбранные значения не принимаются.
Результат

Проблема связана с formcontrol и FormArray.

Пожалуйста, помогите!

Спасибо.

Ответ №1:

Вы можете использовать функцию (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>
 

Typescript

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

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

Нет необходимости упоминать, что вам также придется иметь дело с невыбранными элементами, но вам решать, как их удалить.