基於ng-alain定義自己的select元件

莫沫達發表於2018-12-12

1、首先是my-select2.component.html頁面,這裡是在ng-alain的select基礎上根據業務需求新增新的功能;程式碼如下:

<nz-select #select style="width:100%;" [(ngModel)]="selectedOption" [nzPlaceHolder]="myPlaceHolder" nzAllowClear [nzShowSearch]="true" [nzNotFoundContent]="'無匹配'">
    <nz-option
        *ngFor="let option of options"
        [nzLabel]="option.label"
        [nzValue]="option"
        [nzDisabled]="option.disabled">
    </nz-option>
</nz-select>
複製程式碼

2、再者是my-select2.component.ts頁面,程式碼裡面有註釋;程式碼如下:

import { ControlValueAccessor } from '@angular/forms/src/directives';
import { Component, forwardRef, Input,OnInit,ElementRef,Output,EventEmitter} from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { Router, NavigationEnd } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { SelectService } from './my-select2.service';
declare var $: any;
@Component({
  selector: 'nz-select2',
  templateUrl: './my-select2.component.html',
  providers: [ 
          {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => NzSelect2Component),//注入表單控制元件
            multi: true
          }]
})
export class NzSelect2Component implements OnInit{
   constructor(private selectService:SelectService) { 
    }
  innerValue: any = ''; 
  //監聽繫結的值,與外岑的ngModel相互繫結
  set selectedOption(val:any){
      if (val !== this.innerValue) {
            this.innerValue = val;
            this.onChangeCallback(val.value);
            this.dataBack.emit(val.value);  // 事件
        }
  }
  get selectedOption():any{
       return this.innerValue;
  }
  options = [];//接收select的陣列
   _dataSource:any;//接收本地的自定義陣列或者請求返回的陣列
  @Input()
  url:any;//請求的url
  @Input()
  myPlaceHolder:any;//自定義的PlaceHolder
  @Input()
  //下拉框的資料格式
    fieldKey:any = {
        text: 'text',
          value: 'value'
    };
  @Input()
    set dataSource(val: any) {
        this._dataSource = val;
        if ($.isArray(this._dataSource)) {      
        this.options=this._dataTransform(this._dataSource);//如果是本地陣列或直接請求的陣列直接複製
        }
    }
    get dataSource(): any {
        return this._dataSource;
    }
  @Output() dataBack = new EventEmitter<any>();
  registerOnChange(fn: (value: any) => void) { 
     this.onChangeCallback = fn;
  }
  registerOnTouched(fn: any) {
     this.onTouchedCallback = fn;
  }
    writeValue(value: string) {

    }
  onChangeCallback = (value: any) => {};
  onTouchedCallback = (value: any) => {};
  ngOnInit() {
         //如果url存在則直接請求
        if(this.url){
            this.selectService.getValue(this.url).subscribe(data => { 
               data = data.rows || data.data;        
               this.options=this._dataTransform(data);
            });
        }     
  }
  //轉換下拉框下的欄位
   _dataTransform(data: Array<any>){
       let _data = [];
       for (let i = 0; i < data.length; i++) {
          _data[i] = {};
          _data[i].label = data[i][this.fieldKey.text];
          _data[i].value = data[i][this.fieldKey.value];
        }
        return _data;
  }
}
複製程式碼

3、然後是my-select2.service.ts頁面,這裡主要是請求後臺介面返回的下拉陣列,url為父元件傳過來的連結,程式碼如下:

import { Injectable } from '@angular/core';
import { Headers, Http, URLSearchParams,RequestOptions } from '@angular/http';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import 'rxjs/add/operator/toPromise';
// import { environment } from '../../environments/environment';
@Injectable()
export class SelectService {
    constructor(private http: HttpClient) {}
    getValue(url: any):any{
       return this.http
            .get(url);
      
    }
}
複製程式碼

4、然後是myselect.module.ts頁面,這裡,使用該元件的前提是要引入 import { NzSelectModule } from 'ng-zorro-antd',程式碼如下:

  import { NgModule, ModuleWithProviders }       from '@angular/core';
import { CommonModule }   from '@angular/common';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { NzSelect2Component }  from './my-select2.component';
import { SelectService } from './my-select2.service';
import { NzSelectModule } from 'ng-zorro-antd';
@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        NzSelectModule,
        ReactiveFormsModule
    ],
    exports:[
        NzSelect2Component
    ],
    declarations: [
        NzSelect2Component
    ],
    providers: [
         SelectService
    ]
}) 

export class MySelectModule {
    constructor() {

    }
}

複製程式碼

5、使用方法,在你需要的模組引入:MySelectModule

   import { MySelectModule } from 'bizapp/base/components/myselect/myselect.module';
複製程式碼

6、如何呼叫:url為請求後臺的介面,fieldKey為陣列的格式,這裡可以根據後臺返回來的格式定義這裡的欄位,如:後臺返回格式為[{dmsm1:5,dmz:5}]則fieldKey的定義如下,myPlaceHolder為初始化時顯示的內容,如果是本地陣列,則只需要加上[dataSource]="peer",這裡的peer為本地陣列

    <nz-select2  [url]="'analysis/api/data/code/list/030107'" [(ngModel)]="search2.hpzl" [fieldKey]="{text:'dmsm1',value:'dmz'}" [myPlaceHolder]="'號牌種類'"></nz-select2>
複製程式碼

7、總結:通過這個元件,我們只需要修改url和fieldKey就可以在任意模組引入然後使用,減少程式碼的使用,方便維護


相關文章