2017-07-31 39 views
2

根据我的plunker(在下面的commnet框查看plunker)每当我从第一行改变国家,然后绑定相应的下一个整列的状态下拉insted第一one.i要绑定状态下拉相应国家下拉,但在同一行。帮助将不胜感激。如何使用Angular 4打字稿绑定表中的级联下拉菜单?

+2

http://plnkr.co/edit/BkDk9wLB3J5Uv2ijEX6i?p=preview:瞧这plunker – LGB

+0

请在问题本身的plunker,并与相关的代码提取伴随着它。否则,如果抢劫者得到解决,这个问题将是没有用的任何未来的用户 –

回答

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

+0

谢谢你......它对我有用...... –

+0

如果你的问题得到解决,请标记为“Accepted”。 – Nehal

+1

@Nehal:它已被取消......你能否告诉我如何对这种类型的绑定进行验证。谢谢。 – LGB

1

的级联国家创建一个指示和状态下拉。通过使用指令,Formomodule模板验证在Angular 4中开箱即可使用。

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

Plunker example