如何使用Angular 4 typescript绑定表中的级联下拉列表?
根据我的plunker查看commnet框下方的plunker,每当我从第一行更改国家,然后相应地绑定下一整列的状态下拉列表,而不是第一列。我想相应地绑定状态下拉列表,但仅在同一行中。任何帮助都将不胜感激 代码中的问题是没有区分每个状态下拉列表。您对所有三个国家都使用相同的状态,因此当您更改一个国家的状态列表时,您也会重置其他两个国家 我对代码进行了一些调整,以使用数字索引,这样每个状态下拉列表都会维护自己的列表,并且可以单独设置,而不会影响其他列表 组件1.ts:如何使用Angular 4 typescript绑定表中的级联下拉列表?,angular,angular2-forms,typescript-typings,Angular,Angular2 Forms,Typescript Typings,根据我的plunker查看commnet框下方的plunker,每当我从第一行更改国家,然后相应地绑定下一整列的状态下拉列表,而不是第一列。我想相应地绑定状态下拉列表,但仅在同一行中。任何帮助都将不胜感激 代码中的问题是没有区分每个状态下拉列表。您对所有三个国家都使用相同的状态,因此当您更改一个国家的状态列表时,您也会重置其他两个国家 我对代码进行了一些调整,以使用数字索引,这样每个状态下拉列表都会维护自己的列表,并且可以单独设置,而不会影响其他列表 组件1.ts: export class C
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:
为级联国家和州下拉列表创建指令。通过使用指令,formmodule模板验证在Angular 4中开箱即用 我使用指令扩展了Nehal的plunker示例。我提供的plunker示例没有实现验证
:查看此plunker请在问题中包含plunker,并随附相关代码摘录。否则,如果plunker被修复,这个问题将对任何未来的用户都没有用处。如果您的问题得到解决,请将其标记为已接受。@Nehal:它已被接受……您还可以告诉我如何对这种类型的绑定应用验证。谢谢。
<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>