首页 > 解决方案 > 如何在 Angular 2 中映射和绑定数据?

问题描述

我有两个列表,一个是城市列表,另一个是国家列表。假设如果我单击德里(在城市列表中)。印度将被自动选中。国家/地区列表来自后端。这是一个未完成的演示。演示链接 给我一些关于应该接近什么或如何实现它的建议。截屏

标签: javascriptangulartypescript

解决方案


我会做以下事情。我不会创建仅包含城市名称的列表 city1 和 city2 ,而是创建一个界面来存储城市名称和国家/地区名称,以便您稍后可以使用国家/地区来选择另一个列表。

export interface City {
cityName: string;
country: string;
}

然后我会创建两个这样的列表(在构造函数之前):

  cityList1: City[] = [{cityName: 'delhi',country:'India'},
    {cityName: 'rudrapur',country:'India'},
    {cityName: 'kanpur',country:'India'}];
  selectedCity1: City = this.cityList1[0];
  countrySelectedInList1: string;

  cityList2: City[] = [{cityName: 'washington DC',country:'USA'},
    {cityName: 'New york',country:'USA'}];
  countrySelectedInList2: string;

现在你也有了国家。然后在您的app.component.html 中,我会将您的选项更改为:

<div class="container row">
                <div class="col-sm-6">
                  <p align="left" style="margin-left: -25px;" class="col-sm-3" >City1:</p>
                  <select class="col-sm-3" (ngModelChange)="changeCity1($event)" 
                  [style]="{'width':'140px'}" [ngModel]="selectedCity1">
                    <option  *ngFor="let city of cityList1" [ngValue]="city">{{city.cityName}}</option>
                  </select>
                </div>
              </div>
              <div class="container row">
                <div class="col-sm-6">
                  <p align="left" style="margin-left: -25px;" class="col-sm-3" >City2:</p>
                    <select class="col-sm-3" (ngModelChange)="changeCity2($event)" 
                  [style]="{'width':'140px'}" [ngModel]="selectedCity2">
                    <option  *ngFor="let city of cityList2" [ngValue]="city">{{city.cityName}}</option>
                  </select>
                </div>
              </div>

最后,在app.component.ts中,您需要在单击和更改选项列表时执行以下函数:

changeCity1(value:City){
    this.countrySelectedInList1 = value.country;
  }
  changeCity2(value:City){
    this.countrySelectedInList2 = value.country;
  }

因此,现在您将国家/地区存储在变量this.countrySelectedInList1this.countrySelectedInList2中。因此,您只需要使用该变量更改所选国家/地区。您可以在我上面写给您的函数中使用名为selectedWindingProtection的变量以及变量 countrySelectedInList1 和 countrySelectedInList2 来做到这一点(我在这里不是很具体,因为您在 StackBlitz 中发布的代码此时还不完整)。


推荐阅读