如何使用Angular 4打字稿绑定表中的级联下拉?

时间:2017-07-31 11:42:55

标签: angular angular2-forms typescript-typings

根据我的plunker(在下面的commnet框中看起来),每当我从第一行更改国家时,然后相应地绑定下一个整列的第一个状态下拉列表。我想相应地绑定状态下拉列表但是在只有同一行。任何帮助将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

代码中的问题是您没有区分每个州的下拉列表。您对所有三个使用相同的states,因此当您更改一个国家/地区的州名单时,您也会重置另外两个国家/地区列表。

我稍微调整了代码以使用number索引,这样每个状态下拉列表都会保留自己的列表,并且可以单独设置而不影响其他列表。

component.ts:

export class CountryListComponent implements OnInit {

  initState = new State(0, 0, 'Select');
  selectedCountry:Country[] = []; 
  countries: Country[];
  states: State[] = [];

  allStates: State[] = [];

  constructor(private _dataService: DataService) {
    this.selectedCountry = [new Country(0, 'India', this.initState),new Country(0, 'India', this.initState),new Country(0, 'India', this.initState)]; 
    this.numbers = Array(3).fill().map((x,i)=>i);
    this.countries = this._dataService.getCountries();
    this.states = [[], [], []]
  }

  ngOnInit(){
    this.allStates = this._dataService.getStates();
  }

  onSelect(countryid,index) {
    console.log(countryid, index)
    this.states[index] = this.allStates.filter((item)=> item.countryid == countryid));
    console.log(this.states);
  }

  onStateSelect(stateid, index){
    console.log(stateid, index);
    this.selectedCountry[index].state = this.allStates.filter((item)=> item.id == stateid));
    console.log(this.selectedCountry[index].state);
  }
}

HTML:

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

Plunker demo

答案 1 :(得分:1)

为级联国家/地区下拉创建指令。通过使用指令,formmodule模板验证在Angular 4中开箱即用。

我使用指令从Nehal扩展了plunker样本。我提供的plunker示例没有实现验证。

Plunker example

相关问题