最近遇到了不少问题,真的是命运多舛。Angular真是让人又爱又恨的框架,恨的是资料太少,遇到问题无从下手。爱的是许多其他框架难以做到的功能,angular却可以轻松做到。
话不多说,最近遇到了一个旧项目改造的问题。拿到前同事做的页面效果:
第一眼就看到了这三个下拉框,按捺不住好奇心的我点了点。原来,第一个下拉框可以选择市属和省属,如果选择市属,那么后面就会出现市、县级两个下拉框,如果是省属,那就隐藏了,这个挺容易的。然后就是要选择市之后,区下拉框要有对应区县选项。emmmm,很典型的二级联动,不过既然分析完了思路,那就开始做吧!首先呢,数据肯定要从后端同事那里拿,调用他的接口把数据填充进去。看看数据是什么样子的:
数据略多,就不全部贴出来了。把实体bean创建一下,
// 市级实体类
export class City {
// 市级id
cityId: string;
// 所属类型(0.市属 1.省属)
cityType: number;
// 市级名称(可选属性,若cityType为1时,可不填)
cityName: string;
// 所属区县
counties?: Array;
}
// 区县级实体类
export class Country {
// 区县id
countryId: string;
// 区县名称
countryName: string;
}
// 填写市县类
export class CityAndCountry {
// 市级id
cityId: string;
// 县级id
countryId: string;
// 市级类型
cityType: number;
// 市县级实体构造器
constructor() {
// 给市级id赋予一个真实城市的id初始值
this.cityId = '***';
// 同上
this.countryId = '***';
// 同上
this.cityType = 0;
}
}
实体完成了,开始准备获取数据并填充至实体:
// 二级联动组件
export class CityAreaComponent implements OnInit, onDestroy {
// 结果码 (用于页面处理显示标识)
result_code: number;
// 市级实体声明
city: City[];
// 县区级实体声明
country: Country[];
// 市县、区级填写实体声明
cac: CityAndCountry;
// 声明订阅对象
subscript: Subscription;
constructor (private service: CityService) {
// 结果码 (-1.网络或其他异常 0.无内容 1.请求成功 2.请等待)
this.result_code = 2;
// 初始化填写市区、县级填写实体
cac = new CityAndCountry();
// 初始化数组(这步很重要,有很多人说使用数组相关函数会报未定义异常,是因为没有初始化的原因)
this.city = [];
this.country = [];
// 初始化订阅对象
this.subscript = new Subscription();
}
ngonInit(): void {
this.getCityArea();
}
getCityArea() {
this.subscript = this.service.getCityArea().subscribe(res => {
const result = res.json();
switch (result['code']) {
case 200:
this.result_code = 1;
this.city = json['city'];
break;
}
}, err => {
this.result_code = -1;
console.error(err);
});
}
ngonDestroy(): void {
this.subscript.unsubscribe();
}
}
由于此处是单服务请求,为了让代码比较清晰直观,这里我就不做封装处理了。数据获取了之后就该填充到展示界面了:
这时候,我们发现县级获取起来好像并不能直接获取,怎么办呢?我突然想到,我在ts里面声明一个变量获取市级选择的id号,然后再拿id去找下属县区,这样就可以轻松拿到了。既然要实时获取变化,那我们就实现检测变化钩子:
// 二级联动组件
export class CityAreaComponent implements OnInit, OnDestroy, DoCheck{
// 声明县区级数组
country: Array;
constructor() {
country = [];
}
ngDoCheck(): void {
for (let i = 0; i < this.city.length; i++) {
if (this.city[i].id == this.cac.countryId) {
this.country = this.city[i].counties;
}
if (this.country.length > 0) {
this.cac.country.id = this.country[0].id;
}
}
}
}
最后再补上区县级下拉框:
到此为止,大功告成,再也不用去依赖别人的库了。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



