以垫选择动态反应形式更新选项

时间:2019-02-08 22:12:48

标签: angular angular-reactive-forms

你好,我想知道如何更新在Angular 7中具有动态形式的动态创建的mat-select内的选项,它具有以下结构:

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

我有一种带有回叫功能的垫子选择,应该填充用户的其他垫子选择的dependind onb选择,我只知道要更新选项的垫子选择的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一起使用。

再次感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我假设您有一个this.props.token=token,您需要从中handleOnSuccess进行筛选,并根据第一个选择在第二个垫选择选项中显示。

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

因此,模板中的内容类似

array of objects

<mat-option *ngFor="let opt of item.options | myfilter:cargaId" [value]="opt.key"> 是第一个垫选的选定ID。

然后在您的管道中过滤项目。这样的选项

cargaId

希望这会有所帮助!干杯!

相关问题