gpt4 book ai didi

javascript - Angular 选择选项

转载 作者:行者123 更新时间:2023-12-01 00:42:06 26 4
gpt4 key购买 nike

我有城市的选择选项,我希望当我选择州时,与该州相关的城市显示在第二个选择字段中。

屏幕截图

状态列表

one

城市列表

two

代码

HTML

<ion-item>
<ion-label>Pilih Province</ion-label>
<ion-select formControlName="province_id" multiple="false" placeholder="Pihil Province">
<ion-select-option *ngFor="let state of states" value="state.province_id">{{state.province}}</ion-select-option>
</ion-select>
</ion-item>

<ion-item>
<ion-label>Pilih Kota</ion-label>
<ion-select formControlName="kota_id" multiple="falsee" placeholder="Pilih Kota">
<ion-select-option value="peperoni">Peperoni</ion-select-option>
<ion-select-option value="hawaii">Hawaii</ion-select-option>
</ion-select>
</ion-item>

toko.page.ts

export class AddTokoPage implements OnInit {

states: any[] = [];

constructor(
private statesService: StatesService, //service for returning states and cities
) { }

ngOnInit() {
this.allStates();
}

//get states list
allStates(){
this.statesService.getStates().subscribe((res) => {
for (let state of res) {
this.states.push(state);
}
});
}
}

Note: obviously in my code above I need cities function and that's where I need your help to get those cities lists.

states.service.ts

export class StatesService {

token: any;

constructor(
private http: HttpClient,
private env: EnvService,
private storage: NativeStorage
) {
this.storage.getItem('token').then((token) => {
this.token = token;
}).catch(error => console.error(error));
}

getStates(): Observable<any> {

const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json, text/plain',
'Content-Type': 'application/json'
})
};
return this.http.get(`${this.env.STATES_URL}`, httpOptions).pipe(
map(states => states.data)
);
}

getCities(id) {
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json, text/plain',
'Content-Type': 'application/json'
})
};
return this.http.get(`${this.env.CITIES_URL}/${id}`, httpOptions).pipe(
map(cities => cities)
);
}
}

知道如何根据所选州获取我的城市列表吗?

最佳答案

当有人选择状态时,您可以监听“ionChange”事件。例如

<ion-item>
<ion-label>Pilih Province</ion-label>
<ion-select formControlName="province_id" multiple="false" placeholder="Pihil Province" #state (ionChange)="onChange(state.value)">
<ion-select-option *ngFor="let state of states" value="state.province_id">{{state.province}}</ion-select-option>
</ion-select>
</ion-item>

并且在监听器中您可以调用您的服务

onChange(value) {
// call your service to fetch cities
console.log(value);
this.cities = /* your success response*/
}

编辑:然后您可以在 HTML 上填充这些城市

<ion-item>
<ion-label>Cities</ion-label>
<ion-select formControlName="cities" multiple="false">
<ion-select-option *ngFor="let city of cities | async" value="city.city_id">{{city.name}}</ion-select-option>
</ion-select>
</ion-item>

关于javascript - Angular 选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57651719/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com