首页 >web前端 >js教程 >在angular中基于ng-alain如何定义自己的select组件?

在angular中基于ng-alain如何定义自己的select组件?

亚连
亚连原创
2018-06-05 09:36:563225浏览

这篇文章主要介绍了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