首頁  >  文章  >  web前端  >  在angular中基於ng-alain如何定義自己的select組件?

在angular中基於ng-alain如何定義自己的select組件?

亚连
亚连原創
2018-06-05 09:36:563163瀏覽

這篇文章主要介紹了angular基於ng-alain定義自己的select組件範例,現在分享給大家,也給大家做個參考。

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

<nz-select #select style="width:100%;" [(ngModel)]="selectedOption" [nzPlaceHolder]="myPlaceHolder" nzAllowClear [nzShowSearch]="true" [nzNotFoundContent]="&#39;无匹配&#39;">
  <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 &#39;@angular/forms/src/directives&#39;;
import { Component, forwardRef, Input,OnInit,ElementRef,Output,EventEmitter} from &#39;@angular/core&#39;;
import { NG_VALUE_ACCESSOR } from &#39;@angular/forms&#39;;
import { Router, NavigationEnd } from &#39;@angular/router&#39;;
import { FormGroup, FormBuilder, Validators } from &#39;@angular/forms&#39;;
import { SelectService } from &#39;./my-select2.service&#39;;
declare var $: any;
@Component({
 selector: &#39;nz-select2&#39;,
 templateUrl: &#39;./my-select2.component.html&#39;,
 providers: [ 
     {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => NzSelect2Component),//注入表单控件
      multi: true
     }]
})
export class NzSelect2Component implements OnInit{
  constructor(private selectService:SelectService) { 
  }
 innerValue: any = &#39;&#39;; 
 //监听绑定的值,与外岑的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: &#39;text&#39;,
     value: &#39;value&#39;
  };
 @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 &#39;@angular/core&#39;;
import { Headers, Http, URLSearchParams,RequestOptions } from &#39;@angular/http&#39;;
import { HttpClient, HttpErrorResponse } from &#39;@angular/common/http&#39;;
import &#39;rxjs/add/operator/toPromise&#39;;
// import { environment } from &#39;../../environments/environment&#39;;
@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 &#39;@angular/core&#39;;
import { CommonModule }  from &#39;@angular/common&#39;;
import { FormsModule,ReactiveFormsModule } from &#39;@angular/forms&#39;;
import { NzSelect2Component } from &#39;./my-select2.component&#39;;
import { SelectService } from &#39;./my-select2.service&#39;;
import { NzSelectModule } from &#39;ng-zorro-antd&#39;;
@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    NzSelectModule,
    ReactiveFormsModule
  ],
  exports:[
    NzSelect2Component
  ],
  declarations: [
    NzSelect2Component
  ],
  providers: [
     SelectService
  ]
}) 

export class MySelectModule {
  constructor() {

  }
}

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

import { MySelectModule } from &#39;bizapp/base/components/myselect/myselect.module&#39;;

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

<nz-select2  [url]="&#39;analysis/api/data/code/list/030107&#39;" [(ngModel)]="search2.hpzl" [fieldKey]="{text:&#39;dmsm1&#39;,value:&#39;dmz&#39;}" [myPlaceHolder]="&#39;号牌种类&#39;"></nz-select2>

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

上面是我整理給大家的,希望今後會對大家有幫助。

相關文章:

詳細解讀Node 定時器知識

#在Es6中有關Generator函數詳細解析

#在JavaScript中利用Array filter() 方法實作壓縮稀疏陣列

以上是在angular中基於ng-alain如何定義自己的select組件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn