角度为2的国家和州下拉列表

时间:2017-03-01 12:10:10

标签: angular drop-down-menu npm

我的表单中有两个下拉列表(<select>标签),用于国家和州。当用户选择国家/地区时,状态字段应自动填充相应的值。这是一个很常见的UI元素。

我试图找到一个帮助我的npm包。找到名为 country-region-selector this package并按照说明操作,但无法让它以角度方式工作。具体来说,我添加了元素并添加了所需的类和其他属性。按类查询甚至会获取所需的元素,但它没有填充。

有没有人知道任何替代的npm软件包或已经证明可以与Angular2一起使用的脚本,或者我更好地用here显示的方式对其进行手工编码。

1 个答案:

答案 0 :(得分:1)

country.ts文件

export class Country {
  constructor(public id: number, public name: string) { }
}

countrylistcomponent.html

    <label>Country:</label> 
<select [(ngModel)]="selectedCountry.id" (change)="onSelect($event.target.value)">
  <option value="0">--Select--</option>
  <option *ngFor="#country of countries" value= {{country.id}}>{{country.name}}</option>
</select>
<br/><br/>
<div>
<label>State:</label>
<select>
  <option *ngIf='selectedCountry.id == 0' value="0">--Select--</option>
  <option *ngFor="#state of states " value= {{state.id}}>{{state.name}}</option>
</select>
</div>

countrylistcomponent.ts

import { Component } from 'angular2/core';
import { DataService } from './dataservice';
import { Country } from './country';
import { State } from './state';

@Component({
  selector: 'my-country-list',
  templateUrl: 'app/countrylistcomponent.html',
  providers: [DataService]
})
export class CountryListComponent {
  selectedCountry:Country = new Country(0, 'India'); 
  countries: Country[];
  states: State[];

  constructor(private _dataService: DataService) {
    this.countries = this._dataService.getCountries();
  }

  onSelect(countryid) {
    this.states = this._dataService.getStates().filter((item)=> item.countryid == countryid);
  }
}

dataservice.ts

import { Injectable } from 'angular2/core';
import { Country } from './country';
import { State } from './state';


@Injectable()
export class DataService {
  getCountries() {
    return [
     new Country(1, 'USA' ),
     new Country(2, 'India' ),
     new Country(3, 'Australia' )
    ];
  }

  getStates() {
   return [
     new State(1, 1, 'Arizona' ),
     new State(2, 1, 'Alaska' ),
     new State(3, 1, 'Florida'),
     new State(4, 1, 'Hawaii'),
     new State(5, 2, 'Gujarat' ),
     new State(6, 2, 'Goa'),
     new State(7, 2, 'Punjab' ),
     new State(8, 3, 'Queensland' ),
     new State(9, 3, 'South Australia' ),
     new State(10, 3, 'Tasmania')
    ];
  }
}

state.ts

export class State {
  constructor(public id: number, public countryid: int, public name: string) { }
}

转到plunker:http://embed.plnkr.co/cuMsdkK6SuTn41uQSeI6