如何在角度2中映射和绑定数据?

时间:2018-09-11 06:27:11

标签: javascript angular typescript

我有两个列表,一个是城市列表,另一个是国家列表。假设我单击德里(在城市列表中)。印度将被自动选择。国家/地区列表来自后端。这是一个未完成的演示。 demo link就应该采取什么方法或如何实现提供了一些建议。 screenshot

1 个答案:

答案 0 :(得分:2)

我将执行以下操作。我将创建一个存储城市和国家名称的界面,而不是创建仅包含城市名称的列表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.countrySelectedInList1 this.countrySelectedInList2 中。因此,您只需要使用该变量来更改所选国家/地区。您可以在上面我写给您的函数中使用名为 selectedWindingProtection 的变量以及countrySelectedInList1和countrySelectedInList2变量来完成此操作(我在这里不是很明确,因为您在StackBlitz中发布的代码目前还不完整点)。

相关问题