【问题标题】:How to show cities on a drop down menu according to the selected country? angular 4如何根据所选国家/地区在下拉菜单上显示城市?角度 4
【发布时间】:2018-06-03 00:01:45
【问题描述】:

我正在连接到网络服务以在 2 个下拉菜单中获取国家和城市,一个用于国家,一个用于城市,现在我希望选择第一个下拉菜单(国家)来打开特定的数组country 仅显示与该国家/地区相关的城市,而不是所有城市,因此我需要从网络服务中提取所选国家/地区数组中的城市数组,任何想法如何动态地做到这一点?这是我可以和你分享的代码,我不能分享更多,因为它属于我的公司,但你可以给我写正确的语法并描述如何动态地做,剩下的我会做:

<select name="city" class="rounded-inputs20 select-select col-md-3">
    <option value="Country" selected="selected">Country</option>
  <option *ngFor="let country of countries.data"  value="countries">{{country.name}}</option>
  </select>

  <select id="sel1" name="Country" class="rounded-inputs20 select-select col-md-3">
    <option value="City" selected="selected">City</option>
    <option *ngFor="let city of countries.data[0].cities" value="cities">        {{city.name}}</option>  

  </select>

如果有什么不明白的,请发表评论,我会为您提供更多描述

【问题讨论】:

  • 如果没有国家选择城市必须是一个空数组?
  • 是的,空数组。
  • 发表了一个答案希望对您有帮助
  • @br.julien 这太棒了,但我从网络服务中提取数据,所以我需要根据国家/地区确定将哪个数组放入城市部分,有什么想法吗?

标签: jquery arrays angular web-services filter


【解决方案1】:

首先,您的选择元素的 *ngFor 是错误的。应该是这样的(请注意,您可以将值从 country.name 更改为任何属性你想从你的国家对象):

<option *ngFor="let country of countries.data"  value="{{country.name}}">{{country.name}}</option>

要查看选择了什么值,您可以将 onChange 方法添加到您的选择元素,这样您将拥有类似的内容:

<select name="city" class="rounded-inputs20 select-select col-md-3" (change)="onCountryChange($event.target.value)">

然后在您的 .ts 文件中,您可以根据所选国家/地区调用其他服务或过滤现有的城市列表。

onCountryChange(country: string): void {
  // get cities based on country OR filter existing cities array
}

【讨论】:

    【解决方案2】:

    所以首先你得到改变:

    在您的 html 中:

    <select name="city" (change)="onSelect($event.target.value)" class="rounded-inputs20 select-select col-md-3">
    

    在您的组件中:

    private cities: any[] = [];
    
    constructor(){}
    
    private onSelect(_country: any){
          this.cities = this.countries.data.filter((country: any) =>
               country.name  === _country);
    

    现在您可以在 cities.cities 上执行 ngFor:

    <option *ngFor="let city of cities.cities" value="city"> 
    

    【讨论】:

    • 我认为你的回答是对的,但你能把完整的代码贴出来吗?
    • 这就是我能为你做的一切。
    • 我的意思是编辑是我能为你做的一切:P 你应该能够复制粘贴它,它应该可以工作。 在问题中 name='''' 更改为记住这一点。
    猜你喜欢
    • 1970-01-01
    • 2018-03-23
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 2020-05-26
    • 2017-08-27
    相关资源
    最近更新 更多