Home Web Front-end JS Tutorial How to define your own select component based on ng-alain in angular?

How to define your own select component based on ng-alain in angular?

Jun 05, 2018 am 09:36 AM
angular definition

This article mainly introduces the example of angular defining its own select component based on ng-alain. Now I share it with you and give it as a reference.

1. The first is the my-select2.component.html page, where new functions are added based on business needs based on ng-alain's select; the code is as follows:

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

2. Furthermore, it is the my-select2.component.ts page. There are comments in the code; the code is as follows:

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

3. Then there is the my-select2.service.ts page, which mainly requests the drop-down array returned by the background interface. The url is the link passed by the parent component. The code is as follows:

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

4. Then comes the myselect.module.ts page. Here, the prerequisite for using this component is to introduce import { NzSelectModule } from 'ng-zorro-antd', the code is as follows :

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() {

  }
}
Copy after login

5. To use, import the module you need: MySelectModule

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

6. How to call: url is the interface for requesting the background, and fieldKey is the format of the array. The fields here can be defined according to the format returned by the background. For example: the background return format is [{dmsm1:5,dmz: 5}]Then the definition of fieldKey is as follows. myPlaceHolder is the content displayed during initialization. If it is a local array, you only need to add [dataSource]="peer", where peer is the local array

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

7, Summary: Through this component, we only need to modify the url and fieldKey to introduce and use it in any module, reducing the use of code and facilitating maintenance

The above is what I compiled for everyone, I hope it will be helpful to everyone in the future .

Related articles:

Detailed interpretation of Node timer knowledge

Detailed analysis of the Generator function in Es6

Use the Array filter() method to compress sparse arrays in JavaScript

The above is the detailed content of How to define your own select component based on ng-alain in angular?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

iOS 17: How to change iPhone clock style in standby mode iOS 17: How to change iPhone clock style in standby mode Sep 10, 2023 pm 09:21 PM

Standby is a lock screen mode that activates when the iPhone is plugged into the charger and oriented in horizontal (or landscape) orientation. It consists of three different screens, one of which is displayed full screen time. Read on to learn how to change the style of your clock. StandBy's third screen displays times and dates in various themes that you can swipe vertically. Some themes also display additional information, such as temperature or next alarm. If you hold down any clock, you can switch between different themes, including Digital, Analog, World, Solar, and Floating. Float displays the time in large bubble numbers in customizable colors, Solar has a more standard font with a sun flare design in different colors, and World displays the world by highlighting

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

Do you know Angular Universal? It can help the website provide better SEO support!

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

The definition and function of MySQL composite primary key The definition and function of MySQL composite primary key Mar 15, 2024 pm 05:18 PM

The composite primary key in MySQL refers to the primary key composed of multiple fields in the table, which is used to uniquely identify each record. Unlike a single primary key, a composite primary key is formed by combining the values ​​of multiple fields. When creating a table, you can define a composite primary key by specifying multiple fields as primary keys. In order to demonstrate the definition and function of composite primary keys, we first create a table named users, which contains three fields: id, username and email, where id is an auto-incrementing primary key and user

What is Discuz? Definition and function introduction of Discuz What is Discuz? Definition and function introduction of Discuz Mar 03, 2024 am 10:33 AM

"Exploring Discuz: Definition, Functions and Code Examples" With the rapid development of the Internet, community forums have become an important platform for people to obtain information and exchange opinions. Among the many community forum systems, Discuz, as a well-known open source forum software in China, is favored by the majority of website developers and administrators. So, what is Discuz? What functions does it have, and how can it help our website? This article will introduce Discuz in detail and attach specific code examples to help readers learn more about it.

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

See all articles