mat-select动态反应形式中的更新选项

问题描述 投票:1回答:1

您好我想知道如何更新动态创建的mat-select中的选项,在Angular 7中使用动态表单,它具有以下结构:

<span *ngIf="item !== undefined">
  <div [formGroup]="form">
    <div [ngSwitch]="item.controlType" class="col s12 m12 l4">
      <mat-form-field *ngSwitchCase="'textbox'" class="example-full-width">
        <input matInput [placeholder]="item.label" [formControlName]="item.key" [id]="item.key" [type]="item.type">
      </mat-form-field>
      <mat-form-field *ngSwitchCase="'dropdown'">
        <mat-select [formControlName]="item.key" [placeholder]="item.label" *ngIf="item.callback==1"
          (selectionChange)="cargaDropDown(item.origenCallBack, item.key);">
          <mat-option *ngFor="let opt of item.options" [value]="opt.key">
            {{opt.value}}
          </mat-option>
        </mat-select>
        <mat-select [formControlName]="item.key" [placeholder]="item.label" *ngIf="item.callback==0">
          <mat-option *ngFor="let opt of item.options" [value]="opt.key">
            {{opt.value}}
          </mat-option>
        </mat-select>
      </mat-form-field>
    </div>
    <div class="errorMessage" *ngIf="!isValid">{{item.label}} is required</div>
  </div>
</span>

我有一种mat-select谁有回调,应该填充dependind onb选择用户一些其他mat-select,我只知道mat-select的formControlName我想要更新选项,我需要知道如何实现这一点,我已经在执行cargaDropDown方法时收到了数据,感谢您的帮助。

更新:

我按照角度页面中的教程:

https://angular.io/guide/dynamic-form

我动态创建了表单,我有两种选择,一个是父,另一个是孩子,我试图实现你的答案,只是将新数据的值分配给项目:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'myfilter',
    pure: false
})
export class MyFilterPipe implements PipeTransform {
    transform(items: any[], selectedCargaId: number): any {
        if (!items || !selectedCargaId) {
            return items;
        }
        // filter items array, items which match and return true will be
        // kept, false will be filtered out
        return items.filter(item => item.options.cargaId === selectedCargaId);
    }
}

但selectedCargaId的值始终为null,从不更新。

我需要分配从服务器中检索的数据,当选择父亲的选项,进入孩子,我希望它与mat-select一起工作。

在任何帮助下再次感谢。

angular angular-reactive-forms
1个回答
0
投票

我假设你有一个array of objects,你需要根据第一个选择的短名单和第二个选择选项显示。

为此,您可以使用已经回答here的管道过滤选项。

所以,你的模板中有这样的东西

<mat-option *ngFor="let opt of item.options | myfilter:cargaId" [value]="opt.key">

其中cargaId是第一个mat-select的选定id。

在你的管道中,过滤item.options就像这样

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'myfilter',
    pure: false
})
export class MyFilterPipe implements PipeTransform {
    transform(items: any[], selectedCargaId: number): any {
        if (!items || !selectedCargaId) {
            return items;
        }
        // filter items array, items which match and return true will be
        // kept, false will be filtered out
        return items.filter(item => item.options.cargaId === selectedCargaId);
    }
}

希望这可以帮助!干杯!

© www.soinside.com 2019 - 2024. All rights reserved.