Home > Web Front-end > JS Tutorial > body text

Detailed explanation of a self-made city and county secondary linkage component in Angular4

小云云
Release: 2018-01-16 09:47:21
Original
1680 people have browsed it

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 = &#39;***&#39;;
    // 同上
    this.countryId = &#39;***&#39;;
    // 同上
    this.cityType = 0;
  }
}
Copy after login

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[&#39;code&#39;]) {
        /** 请求成功,并且有值 */
        case 200:
        /** 改变初始返回码 */
        this.result_code = 1;
        /** 获取并填充数据 */
        this.city = json[&#39;city&#39;];
        break;
        /** 其他情况不重复赘述 */
      }
    }, err => {
      /** 显示预设异常信息提示给用户 */
      this.result_code = -1;
      /** 打印log,尽量使用日志产出 */
      console.error(err);
    });
  }

  /** 生命周期销毁钩子 */
  ngOnDestroy(): void {
    /** 取消订阅 */
    this.subscript.unsubscribe();
  }
}
Copy after login

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>
Copy after login

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;
      }
    }
  }
}
Copy after login

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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template