tealpartners / ng-select2 Goto Github PK
View Code? Open in Web Editor NEWThis project forked from muhammadarsal/ng-select2
Angular 13 wrapper for jQuery select2
Home Page: https://tealpartners.github.io/ng-select2
This project forked from muhammadarsal/ng-select2
Angular 13 wrapper for jQuery select2
Home Page: https://tealpartners.github.io/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.
please have a look.
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.
Currently when hoving on a selected item, whose class is '.select2-selection__choice', the title attribute will be added to the element, so is there a way that can overwrite ot remove the title attribute via the options?
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'.
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.
No.
Browser auto-complete can fill the dropdown, but Angular never receives the value.
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
None.
> 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:
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.
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)?
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
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,
}
};
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
}
};
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;
}
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
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
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;
}`
<ng-select2 [data]="exampleData"
[options]="options"
[width]="500"
[(ngModel)]="value">
Selected values: {{ value }}
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
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)
ERROR in src/app/app.module.ts:18:5 - error NG6001: Cannot declare 'NgSelect2Module' in an NgModule as it's not a part of the current compilation.
18 NgSelect2Module
~~~~~~~~~~~~~~~
node_modules/ng-select2/lib/ng-select2.module.d.ts:4:22
4 export declare class NgSelect2Module {
~~~~~~~~~~~~~~~
'NgSelect2Module' is declared here.
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?
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?
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.
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.
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 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.
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.
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:
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.
Hi, I'm using a Linux distro and I tried to start my Angular 12 App, one of these dependencies is ng-select2. When I tried to start the app, appear this error.
Error: The target entry-point "ng-select2" has missing dependencies:
Hi @icecoldfire
How can I set 'required' functionality in order to mark with red border or something else when control is touched or dirty, but no value have been selected?
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.
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
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?
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.
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
I need to add custom class if value empty like bootstrap is-invalid
https://getbootstrap.com/docs/5.1/forms/validation/#custom-styles
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.)
First, many thanks for this fabulous component
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'
Console shows one message:
set value with car2
Console shows 2 messages:
set value with [object Object]
set value with car2
How to avoid this behavior ?
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);
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.
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
<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:
exampleData
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.
How do i use a custom search function
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.