Angular4自制一个市县二级联动组件示例(2)
由于此处是单服务请求,为了让代码比较清晰直观,这里我就不做封装处理了。数据获取了之后就该填充到展示界面了:
<!-- 所属类型(此处固定,一般为获取后端数据字典数据) -->
<select class="city_type" [value]="cac.cityType" [(ngModel)]="cac.cityType">
<!-- 所传内容为整数型 -->
<option value=0>市属</option>
<option value=1>省属</option>
</select>
<!-- 市级选择(类型为省属时隐藏) -->
<select class="city" [value]="cac.cityId" [(ngModel)]="cac.cityId" *ngIf="city.cityType==0">
<!-- 遍历城市数组 -->
<option *ngFor="let opt of option" [value]="opt.cityId">{{opt.cityName}}</option>
</select>
这时候,我们发现县级获取起来好像并不能直接获取,怎么办呢?我突然想到,我在ts里面声明一个变量获取市级选择的id号,然后再拿id去找下属县区,这样就可以轻松拿到了。既然要实时获取变化,那我们就实现检测变化钩子:
// 二级联动组件
export class CityAreaComponent implements OnInit, OnDestroy, DoCheck{
// 声明县区级数组
country: Array<Country>;
constructor() {
/** 重复代码不赘述 */
/** 初始化数组 */
country = [];
}
/** 生命周期检测变化钩子 */
ngDoCheck(): void {
/** 遍历市级数组 */
for (let i = 0; i < this.city.length; i++) {
/** 若选择的市级id和市级数组中的id相吻合 */
if (this.city[i].id == this.cac.countryId) {
/** 将该索引下的counties数组赋予给区县级数组 */
this.country = this.city[i].counties;
}
/** 我们无法避免直辖市的情况,所以多一重判断 */
if (this.country.length > 0) {
/** 为了用户体验,我们要尽量在用户选择市级城市后,默认选择一个区县级城市 */
this.cac.country.id = this.country[0].id;
}
}
}
}
最后再补上区县级下拉框:
<!-- 区县级下拉框 -->
<select [value]="cac.countryId" [(ngModel)]="cac.countryId" *ngIf="cac.cityType==0 && country.length > 0">
<option *ngFor="let count of country" [value]="count.id">{{count.name}}</option>
</select>
到此为止,大功告成,再也不用去依赖别人的库了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持黑区网络。
