省市区三级联动组件 material angular2

前言

最近在写一个项目,其中用到省市区的三级联动组件。起初,由于时间紧凑,使用的是第三方的一个联动组件。但是,回过头来发现,整个组件的风格与整个网站的material风格不相符合,心里难受,就自己动手写了这么一个组件,该组件是建立在Google的angular material2的基础之上进行编写的,下面我将记录编写的整个流程。

组件效果图

省市区三级联动组件 material angular2_第1张图片
效果图

组件分析

1.需要配置@angular/material,配置的问题本文不做具体的讲述,可以访问下面的链接进行配置点击此处(需要翻X)
组件会使用到angular material中的MdSelectModule,所以需要导入MdSelectModule

2.省市区数据的来源,其实网上有许多json的数据源,而且这些数据源大致都是雷同的,所以我就直接从网上扒下一组比较好处理的json数据源,数据源放在我的服务器上数据源(直接访问的话,可能浏览器编码需要改一下,也可以直接去浏览器后台抓取文件)

3.数据搞定之后,就来看一下组件的代码部分

  • three-link.service.ts代码部分
import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';

const ThreeLinkUrl = 'src/mock-data/three-link.json';
@Injectable()
export class ThreeLinkService {
  constructor(public _http: Http) {
  }

  public setAll() {           //获取json中的数据
    return this._http.get(ThreeLinkUrl)
      .map((response: Response) => {
          const res = response.json();
          return res;
      })
      .catch((error: any) => Observable.throw('Server error' || error));
  }
}

这里我请求了存放在mock-data文件夹中的three-link.json文件,使用的是rxjs的方法。之后的component中将调用服务的setAll()函数

  • three-link.component.ts代码部分
mport {Component, OnInit} from  '@angular/core';
import {ThreeLinkService} from './three-link.service';

@Component({
  selector: 'app-three-link',
  templateUrl: './three-link.html',
  styleUrls: ['./three-link.css']
})
export class ThreeLinkComponent implements OnInit {
  public all: Array;                         //存储所有的省市区数据
  public provinces: Array;                    //存储省的信息
  public citys: Array;                       //存储城市的信息
  public areas: Array;                         //存储地区的信息
  public cityValue: string;                               //重置城市选择器时用到的变量
  public areaValue: string;                            //重置地区选择器时用到的变量
  constructor(public threeLinkService: ThreeLinkService) {

  }
  ngOnInit() {
    this.setAll();
  }

  private setAll() {
    this.threeLinkService.setAll()
      .subscribe(
        data => {
          this.all = data;
          this.provinces = this.setProvinces();
        },
        error => {
          console.log(error);
        }
      );
  }

  private setProvinces() {
    if (this.all !== undefined ) {
      const result = new Array();
      for (let i = 0; i < this.all.length; i++) {
        const value = this.all[i];
        if (value['item_code'].slice(2, 6) === '0000') {
          result.push(value);
        }
      }
      return result;
    }
  }

  private setCity(province: string) {
    if (this.all !== undefined) {
      const result = new Array();
      for (let i = 0; i < this.all.length; i++) {
        const value = this.all[i];
        if (value['item_code'].slice(0, 2) === province.slice(0, 2)
          && value['item_code'] !== province && value['item_code'].slice(4, 6) === '00') {
          result.push(value);
        }
      }
      return result;
    }
  }

  private setArea(city: string) {
    if (this.all !== undefined) {
      const result = [];
      for (let i = 0; i < this.all.length; i++) {
        const value = this.all[i];
        if (value['item_code'] !== city && value['item_code'].slice(0, 4) === city.slice(0, 4)) {
          result.push(value);
        }
      }
      return result;
    }
  }

  public selectProvince(code: string) {
    this.cityValue = 'undefined';
    this.areaValue = 'undefined';
    this.citys = this.setCity(code);
  }

  public selectCity(code: string) {
    this.areaValue = 'undefined';
    this.areas = this.setArea(code);
  }
}

整个代码段没必要全部看完,我们可以分成3个部分来进行分析
1.第一部分(初始化省信息部分)

private setAll() {
    this.threeLinkService.setAll()
      .subscribe(
        data => {
          this.all = data;          //将获取的json数据赋值给all数组
          this.provinces = this.setProvinces();            //筛选all数组中所有符合省代码的省信息
        },
        error => {
          console.log(error);
        }
      );
  }

  private setProvinces() {
    if (this.all !== undefined ) {
      const result = new Array();
      for (let i = 0; i < this.all.length; i++) {
        const value = this.all[i];
        if (value['item_code'].slice(2, 6) === '0000') {           //筛选后4位都为0000的json数据
          result.push(value);
        }
      }
      return result;
    }
  }

其中setAll()函数是将threeLinkService中的setAll()返回的数据进行处理,然后将数据赋值给all数组,同时使用setProvince()函数对provinces数组进行赋值。

2.第二部分(根据选择的省信息,获取城市信息)

private setCity(province: string) {
    if (this.all !== undefined) {
      const result = new Array();
      for (let i = 0; i < this.all.length; i++) {
        const value = this.all[i];
        if (value['item_code'].slice(0, 2) === province.slice(0, 2)
          && value['item_code'] !== province && value['item_code'].slice(4, 6) === '00') {  //选择前两位与省代码一样的城市代码,并且后两位为00的数据源  
          result.push(value);
        }
      }
      return result;
    }
  }
public selectProvince(code: string) {
    this.cityValue = 'undefined';       //重置城市选择器
    this.areaValue = 'undefined';         //重置地区选择器
    this.citys = this.setCity(code);
  }

由于整个json数据部分的结构,如下:

{"item_code":"110000","item_name":"北京市"},
  {"item_code":"120000","item_name":"天津市"},
  {"item_code":"130000","item_name":"河北省"},
  {"item_code":"140000","item_name":"山西省"},

所以,我们可以根据字符串的前两位来判断所选择的省,然后获取城市的信息。selectProvince()是一个响应函数,在每次重新选择省时,都需要重置城市选择器和地区选择器。

3.第三部分(根据城市信息,获取地区信息)

private setArea(city: string) {
    if (this.all !== undefined) {
      const result = [];
      for (let i = 0; i < this.all.length; i++) {
        const value = this.all[i];
        if (value['item_code'] !== city && value['item_code'].slice(0, 4) === city.slice(0, 4)) {
          result.push(value);
        }
      }
      return result;
    }
  }
public selectCity(code: string) {
    this.areaValue = 'undefined';        //每次选择城市的同时,都重置地区选择器
    this.areas = this.setArea(code);
  }

地区数据的选择与城市数据的选择一样,都是根据城市的唯一代码进行匹配,将所有匹配的地区数据放入areas数组中

  • html代码部分

  
    {{province.item_name}}
  


  
    {{city.item_name}}
  


  
    {{area.item_name}}
  

省选择器的点击事件就是selectProvince(province.item_code)函数,这函数可以筛选出后续的城市信息,重点要强调的是城市选择器和地区选择器中的[(ngModel)],由于每次重新选择前面一个选择器时,都需要将后面的选择器进行重置,所以这里使用数据的双向绑定的方法,进行选择器的重置,只要将其中的值置为undefined,就可以使选择器重置。

这个组件的原理大致就是这样子,写的有点粗糙,原理可能有些没讲透,希望读者可以给我留言或者提问

注:这篇博文属于原创博文,如果有问题的可以给我留言,转载注明出处。

你可能感兴趣的:(省市区三级联动组件 material angular2)