


Detailed explanation of a self-made city and county secondary linkage component in Angular4
This article mainly introduces an example of a city and county secondary linkage component made by Angular4. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
I have encountered a lot of problems recently, and I am really ill-fated. Angular is really a framework that people love and hate. What they hate is that there is too little information and there is no way to start when encountering problems. What I love is that many functions that are difficult to achieve in other frameworks can be easily achieved in Angular.
Without further ado, I recently encountered a problem with the renovation of an old project. I got the page effect made by my former colleague:
I saw these three drop-down boxes at first glance, and I couldn’t hold back my curiosity and clicked on them. It turns out that in the first drop-down box, you can select municipal or provincial. If you select municipal, then two drop-down boxes of city and county will appear. If it is provincial, it will be hidden. This is quite easy. Then after selecting the city, the district drop-down box must have the corresponding district and county options. emmmm, it’s a very typical two-level linkage, but now that you’ve analyzed the ideas, let’s start doing it! First of all, the data must be obtained from the back-end colleagues and their interfaces are called to fill in the data. Take a look at what the data looks like:
There is a bit too much data, so I won’t post it all. Create the entity bean,
// 市级实体类 export class City { // 市级id cityId: string; // 所属类型(0.市属 1.省属) cityType: number; // 市级名称(可选属性,若cityType为1时,可不填) cityName: string; // 所属区县 counties?: Array<Country>; } // 区县级实体类 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; } }
The entity is completed, start preparing to obtain data and fill it into the entity:
// 二级联动组件 export class CityAreaComponent implements OnInit, OnDestroy { // 结果码 (用于页面处理显示标识) result_code: number; // 市级实体声明 city: City[]; // 县区级实体声明 country: Country[]; // 市县、区级填写实体声明 cac: CityAndCountry; // 声明订阅对象 subscript: Subscription; /** * 构造器 * @param {CityService} service 注入服务 */ 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() { /** 将请求交付服务处理(service代码比较简单,就不贴了) */ this.subscript = this.service.getCityArea().subscribe(res => { /** 获取json请求结果 */ const result = res.json(); /** 判断结果返回码 */ switch (result['code']) { /** 请求成功,并且有值 */ case 200: /** 改变初始返回码 */ this.result_code = 1; /** 获取并填充数据 */ this.city = json['city']; break; /** 其他情况不重复赘述 */ } }, err => { /** 显示预设异常信息提示给用户 */ this.result_code = -1; /** 打印log,尽量使用日志产出 */ console.error(err); }); } /** 生命周期销毁钩子 */ ngOnDestroy(): void { /** 取消订阅 */ this.subscript.unsubscribe(); } }
Since this is a single service request, in order to make the code clearer and more intuitive, I will not encapsulate it here. After the data is obtained, it is time to fill it into the display interface:
<!-- 所属类型(此处固定,一般为获取后端数据字典数据) --> <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>
At this time, we found that it seems that the county level cannot be obtained directly. What should we do? It suddenly occurred to me that I declare a variable in ts to obtain the ID number selected by the municipality, and then use the ID to find the subordinate counties and districts, so that I can get it easily. Since we want to obtain changes in real time, then we implement the change detection hook:
// 二级联动组件 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; } } } }
Finally, add the district and county level drop-down box:
<!-- 区县级下拉框 --> <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>
That’s it, you’re done, you no longer have to rely on other people’s libraries.
Related recommendations:
Ajax combined with php to achieve secondary linkage instance method
js implements Select secondary linkage in HTML Example sharing
Example of provincial and municipal secondary linkage functions implemented by AngularJS
The above is the detailed content of Detailed explanation of a self-made city and county secondary linkage component in Angular4. For more information, please follow other related articles on the PHP Chinese website!

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
