基于另一个下拉式角度改变下拉式选项

问题描述 投票:0回答:2

我在一个预订网站上有两个选择下拉框,其中有3个相同的城市名称。根据第一个下拉框的选择,我希望第二个下拉框的调整方式是不可能有相同的值。

HTML.COMPONENT.TS:我想在第一个下拉框中,根据第一个下拉框中的选择,调整第二个下拉框,使其不能有相等的值。

<h4>Airport of Departure</h4>
    <select name="" id="">
      <option [value]="city" *ngFor="let city of opts">
        {{city.key}}
      </option>
    </select>

    <!-- chosen destination -->

    <h4>Destination (must be different than departure location)</h4>
    <select name="" id="">
      <option [value]="city" *ngFor="let city of opts">
        {{ city.key }}
      </option>
    </select>

COMPONENT.TS:

public cities = ["Warsaw", "Paris", "New York"];
  public opts = [
    { key: "Warsaw", value: ["paris,new york"] },
    { key: "Paris", value: ["warsaw,new york"] },
    { key: "New York", value: ["warsaw, paris,"] }
  ];

STACKBLITZ: https:/stackblitz.comeditflight-date-pikcer。

我有困难,想知道如何使这个方法。谢谢您的支持

angular data-binding dropdown option
2个回答
0
投票

绑定第一个下拉框到一个属性出发。

<h4>Airport of Departure</h4>
    <select name="" id="" [(ngModel)] = "departure">
      <option [value]="city.key" *ngFor="let city of opts">
        {{city.key}}
      </option>
    </select>

在排版中

公共出发:字符串。

第二个下拉菜单:-

<h4>Destination (must be different than departure location)</h4>
    <select name="" id="">
      <ng-container *ngFor="let city of opts">
      <option [value]="city.key" *ngIf="city.key !== departure" >
        {{ city.key }}
      </option>
      </ng-container>
    </select>

1
投票

演示 没有规定所有的飞机都要从一个目的地飞到任何地方,但使用值比使用键更好。

你可以在第二个下拉菜单中使用自定义管道,用大小写感知检查值数组,然后进行过滤。

在html中,只要给第一个下拉菜单一个 [(ngModel)] 双向装订

第二个html用管道

 <option [value]="city.key" *ngFor="let city of opts | departure : dept">

您的定制管

import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
      name: "departure"
})
export class DeparturePipe implements PipeTransform {
   transform(value: any[], dept:string): any {
     return value.filter(x=> !dept || x.value[0].split(",").indexOf( dept.toLowerCase())>-1 )
   }
}

1
投票

如果你只有几个元素,你可以使用[ngValue],但首先你需要改变你的 "选项",如

public opts = [
    { key: "Warsaw", value: ["paris","new york"] },
    { key: "Paris", value: ["warsaw","new york"] },
    { key: "New York", value: ["warsaw", "paris"] }
  ];

你看那个值是一个字符串数组,而不是像你一样是一个唯一的字符串数组(我想是一个排版错误),那么你可以使用简单的

<select [(ngModel)]="departure">
      <option [ngValue]="city" *ngFor="let city of opts">
        {{city.key}}
      </option>
</select>

<select >
      <option [value]="city" *ngFor="let city of departure?.value">
        {{ city }}
      </option>
</select>

但是,要注意的是,"出发 "得到的是所有对象的值,如有值 { key: "Warsaw", value: ["paris","new york"] }

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