【问题标题】:Remove selected option from dropdown after select选择后从下拉列表中删除选定的选项
【发布时间】:2020-01-10 22:44:31
【问题描述】:

如果有来自 API 的任何数据,我需要在视图中显示带有选定值或默认值的下拉列表。我可以使用添加按钮添加新的下拉菜单。但是我必须从下拉列表中选择一次值,所以它不会重复。

我正在使用 ngFor 循环来显示此下拉菜单,并且我正在使用拼接方法从下拉菜单中删除选定的选项。我在这里面临一个问题

示例:如果我从第一个下拉列表 1 和第二个下拉列表中选择汽车 1,我看不到汽车 1,但如果我再次去下拉 1 并将该选项更改为汽车 2,
在下拉 2 中,我看不到 car 1 和 car 2 选项,因为 splice 从该数组中删除了这些选项。

<mat-select required formControlName="productTypeCode"

(selectionChange)="selectType($event.value)">
              <mat-option>Select</mat-option>
              <mat-option *ngFor="let type of newarrayvalues"
                          [value]="type.code">
                {{type.name}}
              </mat-option>
            </mat-select>

PriorExperience -> form array for this dropdowns

  for (let i = 0; i < this.InvestmentTypes.length; i++) {
        for (let j = 0; j < this.PriorExperience.controls.length; j++) {
          if (this.InvestmentTypes[i].code == this.financialDetailsForm.value.piExperience[j].productTypeCode) {
           // this.removedValues.push(this.newarrayvalues[i])
            this.InvestmentTypes.splice(i, 1);
          }
        }

我只需要删除选定的值,如果我更改了应该只从该数组中删除的任何下拉值

请帮帮我。

【问题讨论】:

标签: angular angular-material


【解决方案1】:

您只需要使用过滤功能删除该元素,然后使用表单组再次分配给表单。这解决了我的问题希望这对你也有用。

<mat-form-field class="form-field-width pr-2">
    <mat-select placeholder="Artist" formControlName="artist" multiple>
        <mat-option class="cls-2" *ngFor="let artist of artists" [value]="artist._id">{{
            artist.artistName
        }}</mat-option>
    </mat-select>
</mat-form-field>


removeArtist(type: string){
    if (type === 'artist') {
        this.filterForm.value.artist = this.filterForm.value.artist.filter((stl: string) => stl !== chip._id);
    }
    this.filterForm = this.fb.group({
        artist: [this.filterForm.value.artist, null],
    });
}

【讨论】:

    【解决方案2】:

    因为 splice 从该数组中删除了这些选项。

    不要拼接实际的对象

    用可用数据创建一个Array of objects,对象应该是这样的

    {value: " yourValue", selected: "booleanValue" }
    

    如果在任何下拉列表中选择了该值,只需将 boolean 更改为 true。

    <mat-select required formControlName="productTypeCode"
        (selectionChange)="selectType($event.value)">
            <mat-option>Select</mat-option>
            <ng-container *ngFor="let type of newarrayvalues">
                <mat-option *ngIf="type.selected"
                              [value]="type.value">
                {{type.value}}
            </ng-container>
     </mat-select>
    

    【讨论】:

      【解决方案3】:

      您的问题是他们共享相同的数据。

      如果我是你,我会创建将数组的值作为和 @Input 的组件。然后在该组件中放置删除选项的逻辑。然后在父组件中,您将使用您创建的组件的 fooLoop 进行渲染。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-24
        • 2017-01-11
        • 2014-08-28
        • 2020-11-13
        • 2021-04-16
        • 1970-01-01
        • 1970-01-01
        • 2017-05-19
        相关资源
        最近更新 更多