Giter Site home page Giter Site logo

tealpartners / ng-select2 Goto Github PK

View Code? Open in Web Editor NEW

This project forked from muhammadarsal/ng-select2

28.0 7.0 33.0 2.08 MB

Angular 13 wrapper for jQuery select2

Home Page: https://tealpartners.github.io/ng-select2

TypeScript 83.16% HTML 14.18% JavaScript 2.12% CSS 0.53%
angular select2

ng-select2's Introduction

This package is archived and no longer maintained

You can use @ng-select/ng-select as replacement.











Angular 13 wrapper component of jquery select2 (ng-select2)

npm version License: MIT Actions Status

For Angular version 8.x.x and up. Forked from ng2-select2. Supports two-way data-binding.

Prerequisites

For this plugin to work you need to add two javascript libraries to your project

First install jQuery using npm

npm i -S jquery

Then install select2 using npm

npm i -S select2

Now include their scrpits and styles in your angular.json file

"styles": [
  "styles.css",
  "node_modules/select2/dist/css/select2.min.css"
],
"scripts": [
  "node_modules/jquery/dist/jquery.js",
  "node_modules/select2/dist/js/select2.min.js"
],

Installation

Add package to your project npm i -s ng-select2 (this will save package to your dependencies in package.json)

Basic implementation

  1. Add declaration to your app.module.ts
import { NgSelect2Module } from 'ng-select2';

@NgModule({
  imports: [
    ....,
    NgSelect2Module
  ],
  ...
})
  1. Add it to your template.
<ng-select2 [data]="exampleData"></ng-select2>

Two-way data-binding

<ng-select2 
	[(ngModel)]="fruit"
	[data]="fruitList"
	[placeholder]="'Please select a fruit...'">		
</ng-select2>

Options

Inputs

  • data Array<Select2OptionData>: Data used for generating select2 - inferface definition
  • value string: Default value for select2
  • dropdownParent string: Allows you to customize placement of the dropdown.
  • width string: Set width for the input, default value is resolve
  • disabled boolean: Disable select2, default value is false
  • allowClear boolean: Provides support for clearable selections, default value is false
  • placeholder string: Placeholder for select2
  • id string: Set the id attribute
  • class string: Set the class attribute
  • required boolean: Set the required attribute
  • options Options: Set options for select2, all available options for select2

Outputs

  • valueChanged string | string[]: Emitted when value changes in select2 drop-down

Demos for Angular wrapper for Select2

You can view a live demo here

Every single demo is separate component. Bellow you can find links to components with descriptions.

  • basic demo with only data input
  • disabled value in data array

Demo with options

  • width option
  • theme option
  • multiple option
  • closeOnSelect option

Demo with custom template demo

  • custom template for drop down
  • custom template for select2 input

Demo with data changing demo

  • when you change value in drop down, new value is displayed on the screen
  • you can change selected value
  • you can change select2 data

Demo with dynamic load demo

  • data is loaded with 4 second delay
  • selected value is loaded with 6 second delay

Demo with a multiple options

  • multiple options
  • default value
  • tags

Demo with value changed

  • Demo with value changed output to console log

Demo with allow clear option

  • Demo with allow clear option

Demo with a form

  • Demo with a form

Demo forked from: https://github.com/NejcZdovc/ng2-select2-demo

ng-select2's People

Contributors

arsal-plero avatar dependabot[bot] avatar icecoldfire avatar ircraziesttaxi avatar joaonunesreadinessit avatar nathanclayton avatar sebastien-lamps avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

ng-select2's Issues

When click on clear button, Open drop down again

When user click on clear button (allowclear: true), ng-select2 open drop again. If user wants to change the value, user never click clear icon. so it's better to stop that option or give a option to enable whether user wants re-open drop down again or not.

ng-select2 is not working in Angular 8

i have followed link
https://www.npmjs.com/package/ng-select2/v/1.1.2

component.ts

 import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
 import { FormGroup } from '@angular/forms';
 import { FiltersModal } from 'src/app/CORE/Modals/DataTables/Filters/filters.modal';
 import { Select2OptionData } from 'ng-select2';
 import { Options } from 'select2';
 import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@Component({
 selector: 'test',
templateUrl: './test.component.html'
 })
export class FiltersComponent implements OnInit {


public exampleData: Array<Select2OptionData>;
public options: Options;
public value: string[];
 constructor() { }
 ngOnInit() {

this.exampleData = [
  {
    id: 'multiple1',
    text: 'Multiple 1'
  },
  {
    id: 'multiple2',
    text: 'Multiple 2'
  },
  {
    id: 'multiple3',
    text: 'Multiple 3'
  },
  {
    id: 'multiple4',
    text: 'Multiple 4'
  }
];

this.value = ['multiple2', 'multiple4'];

this.options = {
  width: '300',
  multiple: true,
  tags: true
};
}

onSearchSubmit(btnType: string) {
this.searchSubmitEvent.emit({ button_type: btnType });
 }
    }

component html

		 <ng-select2 [data]="exampleData"
					  [options]="options"
					  [width]="500"
					  [(ngModel)]="value">
		  </ng-select2>
		  <br/>
		  <br/> Selected values: {{ value }}

errors

						vendor.js:11632 Uncaught Error: Template parse errors:
						Can't bind to 'data' since it isn't a known property of 'ng-select2'.
						1. If 'data' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
						2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
						  <h2>6. Multiple values demo (tags)</h2>

						  <ng-select2 [ERROR ->][data]="exampleData"
									  [options]="options"
									  [width]="500"
						"): ng:///Module/FiltersComponent.html@3:14
						Can't bind to 'options' since it isn't a known property of 'ng-select2'.
						1. If 'options' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
						2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("

						  <ng-select2 [data]="exampleData"
									  [ERROR ->][options]="options"
									  [width]="500"
									  [(ngModel)]="value">
						"): ng:///Module/FiltersComponent.html@4:14
						Can't bind to 'width' since it isn't a known property of 'ng-select2'.
						1. If 'width' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
						2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
						  <ng-select2 [data]="exampleData"
									  [options]="options"
									  [ERROR ->][width]="500"
									  [(ngModel)]="value">
						  </ng-select2>
						"): ng:///Module/FiltersComponent.html@5:14
						Can't bind to 'ngModel' since it isn't a known property of 'ng-select2'.
						1. If 'ngModel' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.
						2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("
									  [options]="options"
									  [width]="500"
									  [ERROR ->][(ngModel)]="value">
						  </ng-select2>
						  <br/>
						"): ng:///Module/FiltersComponent.html@6:14
						'ng-select2' is not a known element:
						1. If 'ng-select2' is an Angular component, then verify that it is part of this module.
						2. If 'ng-select2' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("
						  <h2>6. Multiple values demo (tags)</h2>

						  [ERROR ->]<ng-select2 [data]="exampleData"
									  [options]="options"
									  [width]="500"
						"): ng:///Module/FiltersComponent.html@3:2
						No provider for NgControl ("
						  <h2>6. Multiple values demo (tags)</h2>

						  [ERROR ->]<ng-select2 [data]="exampleData"
									  [options]="options"
									  [width]="500"
						"): ng:///Module/FiltersComponent.html@3:2
							at syntaxError (vendor.js:11632)
							at TemplateParser.push../node_modules/@angular/compiler/fesm5/compiler.js.TemplateParser.parse (vendor.js:21180)
							at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._parseTemplate (vendor.js:36295)
							at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileTemplate (vendor.js:36282)
							at vendor.js:36225
							at Set.forEach (<anonymous>)
							at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileComponents (vendor.js:36225)
							at vendor.js:36135
							at Object.then (vendor.js:11623)
							at JitCompiler.push../node_modules/@angular/compiler/fesm5/compiler.js.JitCompiler._compileModuleAndComponents (vendor.js:36134)

package.json

			{
			  "name": "test",
			  "version": "1.0.0",
			  "scripts": {
				"ng": "ng",
				"start": "ng serve",
				"build": "ng build",
				"test": "ng test",
				"lint": "ng lint",
				"e2e": "ng e2e"
			  },
			  "private": true,
			  "dependencies": {
				"@angular/animations": "~8.0.1",
				"@angular/common": "~8.0.1",
				"@angular/compiler": "~8.0.1",
				"@angular/core": "~8.0.1",
				"@angular/forms": "~8.0.1",
				"@angular/platform-browser": "~8.0.1",
				"@angular/platform-browser-dynamic": "~8.0.1",
				"@angular/router": "~8.0.1",
				"angular-datatables": "^8.0.0",
				"bootstrap": "^4.3.1",
				"classlist.js": "^1.1.20150312",
				"datatables.net": "^1.10.19",
				"datatables.net-dt": "^1.10.19",
				"jquery": "^3.4.1",
				"ng-select2": "^1.1.2",
				"ngx-bootstrap": "^5.1.0",
				"popper.js": "^1.15.0",
				"rxjs": "~6.4.0",
				"select2": "^4.0.8",
				"tslib": "^1.9.0",
				"zone.js": "~0.9.1"
			  },
			  "devDependencies": {
				"@angular-devkit/build-angular": "~0.800.0",
				"@angular/cli": "~8.0.4",
				"@angular/compiler-cli": "~8.0.1",
				"@angular/language-service": "~8.0.1",
				"@fortawesome/fontawesome-free": "^5.9.0",
				"@types/datatables.net": "^1.10.17",
				"@types/jasmine": "~3.3.8",
				"@types/jasminewd2": "~2.0.3",
				"@types/jquery": "^3.3.30",
				"@types/node": "~8.9.4",
				"codelyzer": "^5.0.0",
				"jasmine-core": "~3.4.0",
				"jasmine-spec-reporter": "~4.2.1",
				"karma": "~4.1.0",
				"karma-chrome-launcher": "~2.2.0",
				"karma-coverage-istanbul-reporter": "~2.0.1",
				"karma-jasmine": "~2.0.1",
				"karma-jasmine-html-reporter": "^1.4.0",
				"protractor": "~5.4.0",
				"ts-node": "~7.0.0",
				"tslint": "~5.15.0",
				"typescript": "~3.4.3"
			  }
			}

Angular.json

	"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
         
          "node_modules/select2/dist/css/select2.min.css"
        ],
        "scripts": [
          "node_modules/jquery/dist/jquery.js",              
        
          "node_modules/select2/dist/js/select2.min.js"
        ]
      },

Any suggestion is most welcome

Support for SSR

While trying to use server side rendering in my angular 8 application I got following error message:

TypeError: Cannot read property 'off' of at NgSelect2Component.ngOnDestroy

Since jQuery does not work on server side 'this.element' is not defined.
When NgSelect2Component.ngOnDestroy is called, there is not validation that 'this.element' is defined.

By adding a simple validation the bug has been fixed.

#5

How to change options for ng-select2 that's already initialized?

My component sets up the options for my ng-select2, however I would like to change some options later, based on user input.

Currently I can't even do it, if I just change something like this.options.ajax.data = (params) => /*whatever*/;, the change doesn't reflect on ng-select2 components that have already been set up.
For new ones it works, if I dynamically add new ng-select2s and use this same Options instance but with the changed properties, then that select2 will have the changes applied, but not the existing one(s).

Is there a way to provide the [options] as a promise, or something? This is usually how this problem gets solved in other angular components, eg.: angular-datatables.

Or what is the correct method to change options for an existing ng-select2 component (without outright removing it from the DOM and adding it again from scratch)?

ngSelect2 not found in Angualr 9

I'm using Angular 9 and i've done all the instructions in the get started doc
but when i import the ng select lib in my component it tells me that the

ngSelect2 not found

this is how i imported it

import { Select2OptionData } from 'ngSelect2';

exactly like the examples

dropdown is not opening after search in ng select2

Hi

I had problem after search specific keyword dropdown is not opening after search for keyword.

i need to click on textbox then dropdown populates.

html

             <span class="select2-container select2-container--default select2-container--open" style="position: absolute; top: 255px; left: 823.484px;">

Angular code

   this.options = {
  width: '258',
  multiple: true,
  tags: false
};

This class gets hidden after click on textbox its is visible.

Problem

when class "select2-container select2-container--default select2-container--open" is visible after click on textbox.

After Ajax Response this class gets hides.

			changed(search: any) {

					   //call service pass search text to service
						return this.cl.searchFunc(search).subscribe(
						  res1 => 
								  this.select2data = res1.data;
								  this.cd.markForCheck(); // marks path
								 this.cd.detectChanges();
							  }
							}
						  },
						  error => {
							console.log('error  = ', error);
						  });
					  }

Ng select2 class

		import { AfterViewInit, DoCheck, ElementRef, EventEmitter, NgZone, OnChanges, OnDestroy, OnInit, Renderer2, SimpleChanges } from '@angular/core';
		import { ControlValueAccessor } from '@angular/forms';
		import { Select2OptionData } from './ng-select2.interface';
		import { Options } from 'select2';
		export declare class NgSelect2Component implements AfterViewInit, OnChanges, OnDestroy, OnInit, DoCheck, ControlValueAccessor {
			private renderer;
			zone: NgZone;
			_element: ElementRef;
			selector: ElementRef;
			data: Array<Select2OptionData>;
			placeholder: string;
			dropdownParent: string;
			allowClear: boolean;
			value: string | string[];
			width: string;
			disabled: boolean;
			options: Options;
			valueChanged: EventEmitter<{}>;
			private element;
			private check;
			constructor(renderer: Renderer2, zone: NgZone, _element: ElementRef);
			ngDoCheck(): void;
			ngOnInit(): void;
			ngOnChanges(changes: SimpleChanges): void;
			ngAfterViewInit(): void;
			ngOnDestroy(): void;
			private initPlugin;
			private setElementValue;
			writeValue(value: any): void;
			propagateChange: (value: any) => void;
			registerOnChange(fn: any): void;
			registerOnTouched(): void;
		}

Also please guide i need after search list should be empty.

can you please guide anything im missing.

i have replicated problem im using https://github.com/tealpartners/ng-select2/tree/master/src/app/demos/multiple
for static select2 as well as dynamic.

  1. static select2 work fine.
  2. dynamic problem need to click on textbox to open dropdown which is wrong,
    because as soon you search list of data show be available in list.

please have a look.

Reference error jQuery and JQuery

In your template demo, jQuery and jQuery is not found:


// function for result template
  public templateResult = (state: Select2OptionData): JQuery | string => {
    if (!state.id) {
      return state.text;
    }

    let image = '<span class="image"></span>';

    if (state.additional.image) {
      image = '<span class="image"><img src="' + state.additional.image + '"</span>';
    }

    return jQuery('<span><b>' + state.additional.winner + '.</b> ' + image + ' ' + state.text + '</span>');
  }

  // function for selection template
  public templateSelection = (state: Select2OptionData): JQuery | string => {
    if (!state.id) {
      return state.text;
    }

    return jQuery('<span><b>' + state.additional.winner + '.</b> ' + state.text + '</span>');
  }

Cannot find name 'JQuery'.

Cannot find name 'jQuery'.


Is there async support for this wrapper?

I need to use an API to get the data that is going to be displayed in the dropdown. I get the data back from the endpoint but it doesn't show them in the dropdown. It seems the dropdown gets made before I can finish adding the data to my data list. I tried getting the data in the constructor as well but didn't help. How can I load in the data asynchronously? Thank you

ng-select2 with Reactive Forms

Hi guys,
I tried to find something, but everywhere I got, is says that ng-select2 do not support Reactive Forms.
Have you consider implementing that kind of support, or can you tell me if there is an easy workaround for using ng-select2 with Reactive Forms

Best regards,
Julian

NG0100: Expression has changed after it was checked

I am using ng-select2 inside a helper controller

export class DropdownInputComponent implements ControlValueAccessor, OnInit {
@input() data: Array;
.
.
.
constructor(@self() public ngControl: NgControl, private elementRef: ElementRef) {
this.ngControl.valueAccessor = this;
}
.
.
.

}

when adding [formControl]="ngControl.control" to the ng-select2 component and the data is returned by
this.structureService.getAvailableStructures().subscribe(response => {
this.structures = response;
});

An error ExpressionChangedAfterItHasBeenCheckedError is thrown

Trying to install with NPMv7 gives error for incorrect peer dependency

Error message:

# npm resolution error report

2021-09-13T10:59:59.406Z

While resolving: [email protected]
Found: @types/[email protected]
node_modules/@types/jquery
  dev @types/jquery@"^3.5.6" from the root project

Could not resolve dependency:
peer @types/jquery@"^3.6.x" from [email protected]
node_modules/ng-select2
  ng-select2@"^1.2.7" from the root project

Fix the upstream dependency conflict, or retry
this command with --force, or --legacy-peer-deps
to accept an incorrect (and potentially broken) dependency resolution.

Raw JSON explanation object:

{
  "code": "ERESOLVE",
  "current": {
    "name": "@types/jquery",
    "version": "3.5.6",
    "whileInstalling": {
      "name": "client-app",
      "version": "0.0.0",
      "path": "C:\\Source\\MyProject\\ClientApp"
    },
    "location": "node_modules/@types/jquery",
    "isWorkspace": false,
    "dependents": [
      {
        "type": "dev",
        "name": "@types/jquery",
        "spec": "^3.5.6",
        "from": {
          "location": "C:\\Source\\MyProject\\ClientApp"
        }
      }
    ]
  },
  "currentEdge": {
    "type": "dev",
    "name": "@types/jquery",
    "spec": "^3.5.6",
    "from": {
      "location": "C:\\Source\\MyProject\\ClientApp"
    }
  },
  "edge": {
    "type": "peer",
    "name": "@types/jquery",
    "spec": "^3.6.x",
    "error": "INVALID",
    "from": {
      "name": "ng-select2",
      "version": "1.2.7",
      "whileInstalling": {
        "name": "client-app",
        "version": "0.0.0",
        "path": "C:\\Source\\MyProject\\ClientApp"
      },
      "location": "node_modules/ng-select2",
      "isWorkspace": false,
      "dependents": [
        {
          "type": "prod",
          "name": "ng-select2",
          "spec": "^1.2.7",
          "from": {
            "location": "C:\\Source\\MyProject\\ClientApp"
          }
        }
      ]
    }
  },
  "strictPeerDeps": false,
  "force": false
}

Reason inside package.json of node_modules/ng-select2:

"peerDependencies": {
    //...,
    "@types/jquery": "^3.6.x", // only ^3.5.x exists on npmjs.com
    "jquery": "^3.6.x"
  },

I would also note that the ^ symbol ensures the lastest 3.x.x is installed, so it's unnecessary to specify even 3.5.x.

My versions:
Node: v16.9.1
npm: 7.21.1
ng-select2: 1.2.7

Also also, I would advise keeping an eye on this issue and only use jQuery 3.6.0 knowing that it breaks select2 focusing on the searchbox.

Create event for blur or focus out

There are no events for blur or focus out like for a normal dropdown. Please add more events to the same for making this a more complete solution for stylizing the dropdowns.

valueChanged seems to trigger before the actual value has changed, causing any check on the value to get the last one instead of the new one.

I'm using the latest version of ng-select2 in angular8, this is how I'm using it:

<ng-select2 name="item_type" id="item_type" [placeholder]="'Item Type...'" [(ngModel)]="item_type" (valueChanged)="send_item_type()" [data]="item_types_array"> </ng-select2>

if I check the value of item_type in the send_item_type() I get the old one instead of the new one, is there any way to solve this?

edit: code formatting

Change the touched attribute to reflect on blur

As with normal inputs, the "touched" property is set to true after blurring for the first time on the element.
ng select2 is marked as touched after selecting a value for the first time.
As for validation, I am adding the error if the element is touched and invalid but this is not working with ng-select2 since touched is keeping false.
The normal select input is marked touched after blur.

Unable to set default/starting value

There isn't any clear documentation on how to set a default value and I've spent way longer than expected on this.

Using a basic example, how should I set the default value that is shown on page load?

Simple enough implementation:

<ng-select2 [data]="select2OptionData" [(ngModel)]="encoderProfile"></ng-select2>

I've tried using [value], [ngModel], wrapping it in a FormField, and every combination of them. Nothing seems to set the value on page load, it's always blank.

I've gone through all the examples and tried those too, none seem to work, what am I missing here?

I have a problem with the ngmodel, it tells me that I have to have a name

I would like to know if you can help me see how to solve this case.

<ng-select2 [name]="roles" [data]="arrayDataRoles" [(ngModel)]="staffService.selectedStaff.roles" [placeholder]="'Seleccione los roles'" [width]="100" [options]="options">

I use a name because it is what the error asks me.

ERROR Error: If ngModel is used within a form tag, either the name attribute must be set or the form
control must be defined as 'standalone' in ngModelOptions.

  Example 1: <input [(ngModel)]="person.firstName" name="first">
  Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">

I appreciate the help of knowing how to put the name to the input, or what solution could apply.

No valueChanged Update with Browser Autocomplete

I am using ng-select2 for a state dropdown in an address form. If the user selects an address saved for the browser to auto-fill, the ng-select2 state dropdown is populated as well.

Unfortunately (valueChanged) is never called in this scenario where the browser updates the underlying dropdown. There seems to be no way to get the value that the browser populated.

How to do backend search in ng select2

i need to make ajax call .

i need custom search functionality to search records from database.

component.htm

		<ng-select2 [data]="data"
					[options]="options"
					[width]="500",
					[searchFn]="customSearchFn"
				   >DEMO
		</ng-select2>
		<br/>

component.ts

	 customSearchFn(term: string, item) {

		console.log(term);
		console.log(item);

ng2component

		import { AfterViewInit, DoCheck, ElementRef, EventEmitter, NgZone, OnChanges, OnDestroy, OnInit, Renderer2, SimpleChanges } from '@angular/core';
		import { ControlValueAccessor } from '@angular/forms';
		import { Select2OptionData } from './ng-select2.interface';
		import { Options } from 'select2';
		export declare class NgSelect2Component implements AfterViewInit, OnChanges, OnDestroy, OnInit, DoCheck, ControlValueAccessor {
			private renderer;
			zone: NgZone;
			_element: ElementRef;
			selector: ElementRef;
			data: Array<Select2OptionData>;
			placeholder: string;
			dropdownParent: string;
			allowClear: boolean;
			value: string | string[];
			width: string;
			disabled: boolean;
			options: Options;
			valueChanged: EventEmitter<{}>;
			private element;
			private check;
			constructor(renderer: Renderer2, zone: NgZone, _element: ElementRef);
			ngDoCheck(): void;
			ngOnInit(): void;
			ngOnChanges(changes: SimpleChanges): void;
			ngAfterViewInit(): void;
			ngOnDestroy(): void;
			private initPlugin;
			private setElementValue;
			writeValue(value: any): void;
			propagateChange: (value: any) => void;
			registerOnChange(fn: any): void;
			registerOnTouched(): void;
		}

No valueChanged Update with Browser Autocomplete

🐞 Bug report

Is this a regression?

No.

Description

Browser auto-complete can fill the dropdown, but Angular never receives the value.

🔬 Minimal Reproduction

Video of issue: https://drive.google.com/file/d/1pQwY1dJ4lXCBeo0iRnIiufO5Ae9ITQUk/view

Reproduction code in testable form: https://github.com/EpicVoyage/ng-select2/tree/master/src/app/demos/autofill

🔥 Exception or Error

None.

🌍 Your Environment


> ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/
    

Angular CLI: 11.2.14
Node: 12.16.3
OS: win32 x64

Angular: 11.2.14
... animations, cli, common, compiler, compiler-cli, core, forms
... language-service, localize, platform-browser
... platform-browser-dynamic, router
Ivy Workspace: Yes

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1102.14
@angular-devkit/build-angular   0.1102.14
@angular-devkit/core            11.2.14
@angular-devkit/schematics      11.2.14
@angular/http                   7.2.16
@schematics/angular             11.2.14
@schematics/update              0.1102.14
rxjs                            6.6.7
typescript                      4.1.5
webpack                         4.43.0

Anything else relevant?

I originally opened this as #33, but did not have the ability at the time to return with more details. Sorry about that.

I have implemented a potential fix here, including the demo code used in the video:

EpicVoyage@5bfee8e

The addition of the element ID in my forked code would be useful since I have had to resort to hacks to add it in my project, but it is a second change. If you let me know which elements of my code changes you want (if any), I would be happy to create a pull request.

Add headers after init

Hi,

Is there a way to add headers AFTER init ??
I want to add access token to headers with an observable but it's always undefined.


export class TestComponent implements OnInit {
  public options: Options;
  private accessToken: string;

  constructor(public auth: AuthService) {
    this.auth.getAccessToken().subscribe(
      (token: string)  => {
        this.accessToken = token;
      }
    );
  }

  ngOnInit() {
    console.log('ngoninit access token:' + this.accessToken);
    this.options = {
      multiple: false,
      closeOnSelect: true,
      width: '300',
      allowClear: true,
      minimumInputLength: 4,
      language: "fr",
      placeholder: 'Selectionnez la ville...',
      templateResult: this.formatResult,
      templateSelection: this.formatSelection,
      ajax: {
        url: 'http://localhost:8000/api/geo/search',
        dataType: 'json',
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ` + this.accessToken <=== always "undefined"
        },
        data: function (params) {
          return {
            pattern: params.term,
          };
        },
        processResults: function (data, params) {

          //Here data must have array of objects which have "id" & "text" property 	  
          return {
            results: data.data
          };
        },
        cache: true
      }
    };

Wrong value shown when using "tags" option with initial value of null

<ng-select2
	[width]="100"
	[options]="{ tags: true }"
	[formControl]="formControl"
	[data]="exampleData"
	[placeholder]="'Please select a fruit...'">
</ng-select2>

<p>{{formControl.value}}</p>
formControl = new FormControl();
exampleData = [
	{
		id: 'basic1',
		text: 'Basic 1'
	},
	{
		id: 'basic2',
		disabled: true,
		text: 'Basic 2'
	},
	{
		id: 'basic3',
		text: 'Basic 3'
	},
	{
		id: 'basic4',
		text: 'Basic 4'
	}
];

Steps to reproduce:

  1. Enter a custom text that matches none of the items in exampleData
  2. Do not confirm the entered text
  3. Click somewhere else to hide the dropdown

Result:
The select looks as if the first element of exampleData is selected, but the actual value of the formControl remains null and valueChanged is also not fired.

Note: There is also some more weirdness going on here depending on the text entered in Step 1.
If I enter just "a" and click away, nothing happens at first, but when I click on the select, it suddenly shows the first element again.

Can't bind to 'data' since it isn't a known property of 'ng-select2'.

In the
https://www.npmjs.com/package/ng-select2/v/1.1.2

	import { NgSelect2Module } from 'ng-select2';

	@NgModule({
	  imports: [
		....,
		NgSelect2Module
	  ],
	  ...
	})

github package.json

		{
		  "name": "ng-select2",
		  "version": "0.0.0",
		  "dependencies": {
			"@angular/animations": "8.0.1",
			"@angular/common": "8.0.1",
			"@angular/compiler": "8.0.1",
			"@angular/core": "8.0.1",
			"@angular/forms": "8.0.1",
			"@angular/platform-browser": "8.0.1",
			"@angular/platform-browser-dynamic": "8.0.1",
			"@angular/router": "8.0.1",
			"@types/jquery": "3.3.29",
			"@types/select2": "4.0.47",
			"bootstrap": "4.3.1",
			"jquery": "3.4.1",
			"popper.js": "1.15.0",
			"rxjs": "6.5.2",
			"select2": "4.0.7",
			"zone.js": "0.9.1"
		  },
		  "scripts": {
			"ng": "ng",
			"start": "ng serve",
			"build": "ng build",
			"test": "ng test",
			"lint": "ng lint",
			"e2e": "ng e2e",
			"packagr": "ng-packagr -p projects/ng-select2/ng-package.json",
			"packagr-prod": "ng-packagr -p projects/ng-select2/ng-package.prod.json"
		  },
		  "private": true,
		  "devDependencies": {
			"@angular-devkit/build-angular": "0.800.3",
			"@angular-devkit/build-ng-packagr": "0.800.3",
			"@angular/cli": "8.0.3",
			"@angular/compiler-cli": "8.0.1",
			"@angular/language-service": "8.0.1",
			"@types/node": "12.0.8",
			"angular-cli-ghpages": "0.5.3",
			"codelyzer": "5.1.0",
			"ng-packagr": "5.3.0",
			"ts-node": "7.0.1",
			"tslib": "1.9.3",
			"tslint": "5.17.0",
			"typescript": "3.4.5"
		  }
		}

My Package.,json

		 "dependencies": {
		   
			"jquery": "^3.4.1",
			"ng-select2": "^1.1.2",
			"ngx-bootstrap": "^5.1.0",
			"popper.js": "^1.15.0",
			"rxjs": "~6.4.0",
			"select2": "^4.0.8",
			"tslib": "^1.9.0",
			"zone.js": "~0.9.1"
		  },

How can we implement select2 if we don't reference the NPM package but directly in package json

select2 is not defined?

Whenever I am trying to select2 code on the live website its throw error "$select2() is no defined."
but the same code is finely working on my local environment.

Angular Ivy support

When building the branch feature/ivy (b8c57b5) the following errors occurs:

λ ng serve

Date: 2019-06-15T10:46:07.921Z
Hash: 7e9b4a066c2a17fb5694
Time: 10189ms
chunk {main} main.js, main.js.map (main) 1.86 kB [initial] [rendered]
chunk {polyfills} polyfills.js, polyfills.js.map (polyfills) 664 bytes [initial] [rendered]
chunk {polyfills-es5} polyfills-es5.js, polyfills-es5.js.map (polyfills-es5) 357 kB [initial] [rendered]
chunk {runtime} runtime.js, runtime.js.map (runtime) 6.08 kB [entry] [rendered]
chunk {scripts} scripts.js, scripts.js.map (scripts) 339 kB [entry] [rendered]
chunk {styles} styles.js, styles.js.map (styles) 1.17 MB [initial] [rendered]
chunk {vendor} vendor.js, vendor.js.map (vendor) 327 kB [initial] [rendered]

ERROR in Unable to write a reference to NgSelect2Component in ng-select2/projects/ng-select2/src/lib/ng-select2.component.ts from ng-select2/projects/ng-select2/src/lib/ng-select2.module.ts
** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
i 「wdm」: Failed to compile.

It looks related to angular/angular#29361. Any thoughts on this issue?

Error: The target entry-point "ng-select2" has missing dependencies: - Select2

Hi Team,

I was trying to install ng-select2 package in one of my Angular-12.2.7 application, I am being shown with the following message even though I had installed select2 package and listed it in angular.json scripts and styles.

`node_modules/@angular/compiler-cli/ngcc/src/entry_point_finder/targeted_entry_point_finder.js:40
throw new Error("The target entry-point "" + invalidTarget.entryPoint.name + "" has missing dependencies:\n" +
^

Error: The target entry-point "ng-select2" has missing dependencies:

  • Select2`
    image

allowClear doesn't seem to be working

I'm setting allowClear: true in the Options object, and setting a placeholder, but nothing seems to show the clear button. Can you please modify a demo to show off the allowClear functionality?

2 issues on drop down list

  1. When drop down the list and scroll down the page, drop down list get separated. (1st Image)
  2. When pop the spinner, only dropdown list show in front of spinner (I have changed z-index but it's not working). (2nd Image)
    Please refer the blow attached images.

1st Image
1

2nd Image
2

Nested options

Hi, there.
When I try to add nested data, the options are not selectable. Maybe I'm doing in the wrong way.
I build data array like this:
[{'text': 'Cat 1', 'children': [{ 'text': 'Option 1' }] }]
Is this the right way?

initSelection does not get fired

I tried with this fork with reactive forms and it worked well except for the initSelection. am I missing something here? Any help would be greatly appreciated here.

<div [formGroup]="frmContact" aria-labelledby="title"> <ng-select2 shape="semi-round" [options]="Companyoptions" formControlName="CompanyId"></ng-select2></div>

ngOnInit() { this.Companyoptions = this.companyServices.select2StandardOptions(select2Settings); this.frmContact = this.fb.group({ CompanyId: this.fb.control('',[Validators.required]), }); this.frmContact.setValue(result); // update CompanyId as 1 }

` select2StandardOptions(select2Settings: Select2Settings): Options{

let select2Options:Options = {
    width: '100%',
    theme: "bootstrap4",
    placeholder: select2Settings.placeHolderText === undefined ? "Choose..." : select2Settings.placeHolderText,
    minimumInputLength: select2Settings.minimumInputLength === undefined ? 1 : select2Settings.minimumInputLength,
    ajax: {
      transport: function (params, success, failure) {
        let options_ : any = {
          params: params.data
      };
      select2Settings.httpService.get(select2Settings.endPoint, options_).subscribe(
          (res: any) => {
            success(res);                                 
          },
            err => {
              console.log(err);
              if (err.error === undefined){
                failure({
                  results: [],
                  hasError: true,
                  error: err.error.error
                });
              } else {
                success({
                  hasError: true,
                  error: err,
                });
              }               
              },
        );
      },
      quietMillis: select2Settings.quietMillis === undefined ? 200 : select2Settings.quietMillis,
      dataType: 'json',
      delay: 250,
      cache: false,
      data: (params: any) => {
        return {          
              PageNumber: params.page === undefined ? 1 : params.page,
              PageSize: select2Settings.pageSize === undefined ? 15 : select2Settings.pageSize,
              Name: params.term === undefined ? "" : params.term
          }
      },
      initSelection: function(element, callback) {
        // This doesn't get fired.....
        var data =[] 
        data.push({Id:1, text:"SOME COMPANY"})
        callback(data);
        console.log(element);
      },
      processResults: (data: any, params: any) => {
        var resultsArr = [];
        var more = false;
        if (data.hasError) {              
          resultsArr.push({ text: data.error.error.error, dataSet:data.error, disabled: true, loading: true, hasError:true });
          more = false;
        } else {
          if (data[select2Settings.listName].items.length){
            return {
              results: $.map(data[select2Settings.listName].items, function(obj) {
                    return {id: obj[select2Settings.idField], text: obj[select2Settings.txtField], dataSet:obj };
                }),
                pagination: {
                  more: (data[select2Settings.listName].pageNumber * data[select2Settings.listName].pageSize) < data[select2Settings.listName].totalCount
                }
            };
          }
        }
        return { results: resultsArr, pagination: { more: more } };
      },
    },
    templateResult: function (data) {
      if (data.loading !=undefined && data.loading == true){
        if (data.hasError){
          return "Error: " + data.text
        } else {
          return data.text; 
        }
        
      } else {
          if (select2Settings.templateResult.length){
            let htmlStr: string = "<ul class='list-unstyled'>";
            for (let i = 0; i < select2Settings.templateResult.length; i++) {                  
              if (select2Settings.templateResult[i].dataList === ""){
                if (select2Settings.templateResult[i].label === ""){
                  htmlStr += "<li class='lead'>" +data.text + "</li>";
                } else {
                  htmlStr += "<li><small>" + select2Settings.templateResult[i].label + ": " + data.text + "</small></li>";
                }                    
              } else {
                htmlStr += "<li><small>" + select2Settings.templateResult[i].label + ": " + data.dataSet[select2Settings.templateResult[i].dataList][select2Settings.templateResult[i].key] + "</small></li>";
              }
            }
            htmlStr += '</ul>';
            return $(htmlStr);
          }
      }
      
    },
    
}
return select2Options;

}`

Component property is set twice with the two-ways data-binding: first with an object, second with a string

First, many thanks for this fabulous component

Scenario:

In the Demo with data changing demo, change 'value' property with this code:

  private _value: string;
  get value(): string {
    return this._value;
  }
  set value(value: string) {
    console.log('set value with ' + value);
    this._value = value;
  }

And select the value 'Cars 2'

Expected:

Console shows one message:
set value with car2

Actual:

Console shows 2 messages:

set value with [object Object]
set value with car2

How to avoid this behavior ?

PS:

I know that the following lines are the cause of both messages:
ng-select2.component.ts:155

this.valueChanged.emit({
        value: newValue,
        data: this.element.select2('data'),
      });
this.propagateChange(newValue);

Results stuck in the html

This happend at this exactly steps while using with Angular 8 FormGroup:

1: Go to Component.
2: Focus on Input tag, ng-select2 shows up.
3: Click Back button in the browser.
4: Ng-select2 stucked at the screen

Image of the issue:
https://imgur.com/a/IBmH3Ob

ng build failed ng-select2 version 1.2.7

error TS2307: Cannot find module 'Select2' or its corresponding type declarations.

4 import { Options } from 'Select2';

https://www.npmjs.com/package/ng-select2/v/1.2.7

import { Options } from 'Select2';
select2Options: Options = {
...{
multiple: true,
matcher: this.matchCustom,
tags: false,
placeholder: this.placeholder,
language: {
noResults: function () {
return this.getTranslateTag(
'installer_dashboard.users.add_user.no_results_found'
);
},
},
templateSelection: this.formatState,
}
};

image

How to trigger change event with server side select2 to download and render a selected item?

With regular select2 I use this handy function, that I call on the underlying HTML Select element, and basically it loads the data from the provided URL, makes a new option element, appends it to the select element, then triggers both the plain change and select2 specific events.

$.fn.extend({
        preSelect2: function (params) {
            var select = this;
            $.ajax({
                type: 'GET',
                url: params.url
            }).then(function (data) {
                var option = new Option(data.text, data.id, true, true);
                select.append(option).trigger('change');

                select.trigger({
                    type: 'select2:select',
                    params: {
                        data: data
                    }
                });
            });
            return select;
        },
        ...
});

But since 🥕 farming is the future...
How can I do this with ng-select2?

If I change the wired [(ngModel)] on an "unused" select2 (meaning user hasn't selected any values yet), then it doesn't show the selection. However, if the user have selected a specific element before, then changed it to something else (either new value or cleared), then if I change the wired model value to the specific element, the correct element is shown as selection. (But neither times does the (valueChanged) event fire.)

I know that regular select2 appends each new selected value to the DOM permanently, so I assume this wrapper does the same thing (and that's why it's able to "show" a previously selected item, because it already exists in the dom), but I haven't been able to observe such DOM manipulation with dev tools or find the underlying select element and observe what happens when I do some clicky clicky. (Then again I'm still new to Angular, so maybe it does some magic on the fly without it reflecting in the DOM.)

changeValue does not fire

On the latest version (1.2.1) the changeValue event does not fire when a value is selected.

On version 1.1.2 it does work.

Custom array in data property

Can I pass a custom type array in data property, and define which string attribute in the model will be displayed in dropdown? I tried to use formatSelection, formatResult, templateSelection and templateResult, but no luck.

Reference error jQuery and JQuery

Hi @icecoldfire , I'm added jQuery using npm like in doc, here stackblitz demo

my angular.json file:


"scripts": [
              "node_modules/jquery/dist/jquery.js",
              "node_modules/select2/dist/js/select2.min.js"
            ]


and my package.json file:


{
  "name": "frontend",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "~9.0.5",
    "@angular/common": "~9.0.5",
    "@angular/compiler": "~9.0.5",
    "@angular/core": "~9.0.5",
    "@angular/forms": "~9.0.5",
    "@angular/platform-browser": "~9.0.5",
    "@angular/platform-browser-dynamic": "~9.0.5",
    "@angular/router": "~9.0.5",
    "@okta/okta-angular": "2.0.0",
    "@oktadev/schematics": "^1.5.1",
    "jquery": "^3.4.1",
    "ng-select2": "^1.2.2",
    "rxjs": "~6.5.4",
    "select2": "^4.0.13",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.5",
    "@angular/cli": "~9.0.5",
    "@angular/compiler-cli": "~9.0.5",
    "@angular/language-service": "~9.0.5",
    "@types/node": "^12.11.1",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "codelyzer": "^5.1.2",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "~5.4.3",
    "ts-node": "~8.3.0",
    "tslint": "~5.18.0",
    "typescript": "~3.7.5"
  }
}


Originally posted by @niskah-energies in #23 (comment)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.