如何使用 Angular 4 typescript 在 table 中绑定级联下拉菜单?

How to bind cascading drop down in table using Angular 4 typescript?

根据我的 plunker(在下面的 commnet 框看 plunker)每当我从第一行更改国家/地区然后相应地绑定下一整列的第一个状态下拉列表 one.i 想要相应地绑定状态下拉列表国家/地区下拉列表但是在只有相同 row.Any 的帮助将不胜感激。

你的代码中的问题是你没有区分每个状态下拉列表。您对这三个国家使用相同的 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

为级联国家和州下拉列表创建一个指令。通过使用指令,表单模块模板验证在 Angular 4 中开箱即用。

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

Plunker example