nejczdovc / ng2-select2 Goto Github PK
View Code? Open in Web Editor NEWSelect 2 wraper for angular2
License: MIT License
Select 2 wraper for angular2
License: MIT License
NPM package needs improvement. All below will be fixed with new webpack cli.
The cssImport
property pollutes the whole application if it is set to true
on one instance.
I opt for removing it altogether. Users should import the CSS of select2, just like they have to import the JavaScript. A component should not have the power to pollute the global context.
npm install ng2-select2
appears to be broken and peg's CPU to 100% when initializing select2.
I had to grab the version from your plunker demo:
https://unpkg.com/[email protected]/
to fix the issue.
Hi,
So I added this import line into app.module.ts
import { Select2Module } from 'ng2-select2';
upon running the application I got this error
this.element.select2 is not a function
Could you please shed some lights on how to resolve this issue?
Thanks,
Tam
Template Code :
<select2 id="default-select" [data]="rolesSelect2 | async" [width]="250"></select2>
Throwing an error "inline template:4:16 caused by: Invalid argument '' for pipe 'AsyncPipe'"
Component Code :
constructor(private roleService : UserRoleService,private roleAccessService: RoleAccessService) {
this.roleService.getUserRoles().subscribe(res => {
for (let role of res.data)
{
this.rolesSelect2.push({id: role.id, text: role.role_name});
}
});
}
I have this error in red when I serve from my CLI :
ERROR in Select2Module is not an NgModule webpack: bundle is now VALID.
ng build --aot error :
ERROR in Unexpected value 'Select2Module in /Users/Enigma/web/node_modules/ng2-select2/ng2-select2.d.ts' imported by the module 'AppModule in /Users/Enigma/web/src/app/app.module.ts'
ERROR in ./src/main.ts
Module not found: Error: Can't resolve './$$_gendir/app/app.module.ngfactory' in '/Users/Enigma/web/src'
@ ./src/main.ts 4:0-74
@ multi main
ERROR in ./~/@angular/core/src/linker/system_js_ng_module_factory_loader.js
Module not found: Error: Can't resolve '/Users/Enigma/web/src/$$_gendir' in '/Users/Enigma/web/node_modules/@angular/core/src/linker'
@ ./~/@angular/core/src/linker/system_js_ng_module_factory_loader.js 69:15-36 85:15-102
@ ./~/@angular/core/src/linker.js
@ ./~/@angular/core/src/core.js
@ ./~/@angular/core/index.js
@ ./src/main.ts
@ multi main
Any idea ?
OS : macOs Sierra
Related : angular/angular-cli#3426
package.json
{
"name": "web",
"version": "0.0.1",
"license": "MIT",
"angular-cli": {},
"scripts": {
"ng": "ng",
"start": "ng serve",
"lint": "tslint \"src/**/*.ts\"",
"test": "ng test",
"pree2e": "webdriver-manager update --standalone false --gecko false",
"e2e": "protractor"
},
"private": true,
"dependencies": {
"@angular/common": "^2.3.1",
"@angular/compiler": "^2.3.1",
"@angular/core": "^2.3.1",
"@angular/forms": "^2.3.1",
"@angular/http": "^2.3.1",
"@angular/platform-browser": "^2.3.1",
"@angular/platform-browser-dynamic": "^2.3.1",
"@angular/router": "^3.3.1",
"chart.js": "2.3.0",
"core-js": "^2.3.1",
"jquery": "^3.1.1",
"moment": "2.15.2",
"ng2-bootstrap": "^1.1.16-11",
"ng2-charts": "1.4.1",
"ng2-restangular": "^0.1.24",
"ng2-select2": "^1.0.0-beta.6",
"rxjs": "^5.0.2",
"select2": "^4.0.3",
"ts-helpers": "^1.1.1",
"zone.js": "^0.7.2"
},
"devDependencies": {
"@angular/compiler-cli": "^2.3.1",
"@types/jasmine": "2.5.38",
"@types/node": "^6.0.42",
"angular-cli": "1.0.0-beta.24",
"codelyzer": "~2.0.0-beta.1",
"jasmine-core": "2.5.2",
"jasmine-spec-reporter": "2.5.0",
"karma": "1.2.0",
"karma-chrome-launcher": "^2.0.0",
"karma-cli": "^1.0.1",
"karma-jasmine": "^1.0.2",
"karma-remap-istanbul": "^0.2.1",
"protractor": "~4.0.13",
"ts-node": "1.2.1",
"tslint": "^4.0.2",
"typescript": "~2.0.3"
}
}
angular-cli.json
{
"project": {
"version": "1.0.0-beta.24",
"name": "web"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"test": "test.ts",
"tsconfig": "tsconfig.json",
"prefix": "app",
"mobile": false,
"styles": [
"scss/style.scss"
],
"scripts": [
"../node_modules/chart.js/dist/Chart.bundle.min.js",
"../node_modules/chart.js/dist/Chart.min.js",
"../node_modules/jquery/dist/jquery.js",
"../node_modules/select2/dist/js/select2.full.js"
],
"environments": {
"source": "environments/environment.ts",
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"addons": [],
"packages": [],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"prefixInterfaces": false,
"inline": {
"style": false,
"template": false
},
"spec": {
"class": false,
"component": true,
"directive": true,
"module": false,
"pipe": true,
"service": true
}
}
}
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LocationStrategy,
HashLocationStrategy } from '@angular/common';
import { HttpModule, Http } from '@angular/http';
import { FormsModule } from '@angular/forms';
// Components
import { AppComponent } from './app.component';
// Library
import { RestangularModule } from 'ng2-restangular';
import { Ng2BootstrapModule } from 'ng2-bootstrap/ng2-bootstrap';
import { Observable } from "rxjs/Observable";
import { Select2Module } from "ng2-select2";
// Security
import { AuthGuard } from "./_guards/auth.guard";
// Services
import { UserService } from "./_services/user.service";
import { AlertService } from "./_services/alert.service";
import { AuthenticationService } from "./_services/authentication.service";
// Routing
import { AppRoutingModule } from './app.routing';
export function configFunc (RestangularProvider, http) {
RestangularProvider.setBaseUrl('http://localhost:8888/web/');
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
if (currentUser && currentUser.token) {
RestangularProvider.setDefaultHeaders({'Authorization': 'Bearer ' + currentUser.token});
}
}
@NgModule({
imports: [
BrowserModule,
AppRoutingModule,
Ng2BootstrapModule,
Select2Module,
RestangularModule.forRoot([Http], configFunc),
],
declarations: [
AppComponent
],
providers: [
{
provide: LocationStrategy,
useClass: HashLocationStrategy
},
UserService,
AuthenticationService,
AlertService,
AuthGuard
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Hi,
I have a problem with the multi-select....
The method valueChanged used to retrieve the selected data, always returns the first selected element....
For example :
values = [val1, val2, val3, val4]
I select val4, it displays val4, then I select val2, it displays val2, but then I select val3, but still displays val2.... When you select item, they are sorted by text and valueChanged return the id of the first element...
And when you clear one selected element, the event is not emitted...
Is there a solution ?
ng2-select2 supports ngOnChanges for the [data] input.
I'm receving the error in the subject when the input array changes so I've tried converting the array to an observable using Observable.of(inputArray) and the async pipe similarly as to the Dynamic Example but still receiving
EXCEPTION: Expression has changed after it was checked
The only workaround I've found is to set changeDetection: ChangeDetectionStrategy.OnPush in the @component decorator, but that creates problems with other async data in the component.
Any example on how to change the [data] input array programmatically after the component initialization?
Hi, I want to add select2 in my angular2 app for which I wanted to take a look at how to do it via Angular-cli. But your links in the readme.md are not working.
Pressing tab while focused on this component doesn't continue to the next field currently.
Hello @NejcZdovc !
i selected noi_dung_id+1 then i disable noi_dung_id+0 in service but Select2 is not update data ! I'm sorry my English is bad
https://embed.plnkr.co/P2qvUyGA8fTlFXXKHSuB/
Getting an error of jQuery not defined..
ReferenceError: jQuery is not defined
select2.min.js:1:180
Error: (SystemJS) ZoneDelegate.prototype.invoke@https://npmcdn.com/[email protected]/dist/zone.js:203:19
Zone.prototype.run@https://npmcdn.com/[email protected]/dist/zone.js:96:24
scheduleResolveOrReject/<@https://npmcdn.com/[email protected]/dist/zone.js:462:52
ZoneDelegate.prototype.invokeTask@https://npmcdn.com/[email protected]/dist/zone.js:236:23
Zone.prototype.runTask@https://npmcdn.com/[email protected]/dist/zone.js:136:28
drainMicroTaskQueue@https://npmcdn.com/[email protected]/dist/zone.js:368:25
ZoneTask/this.invoke@https://npmcdn.com/[email protected]/dist/zone.js:308:25
Evaluating https://npmcdn.com/@angular/compiler/bundles/compiler.umd.js
Error loading https://npmcdn.com/@angular/compiler/bundles/compiler.umd.js as "@angular/compiler" from https://npmcdn.com/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js
The direct demo does load:
https://nejczdovc.github.io/ng2-select2/
i try to use this api bur i get some error :
Uncaught ReferenceError: require is not defined
at ng2-select2.ts:1
http://localhost:3000/node_modules/ng2-select2/src/select2.component Failed to load resource: the server responded with a status of 404 (Not Found)
localhost/:25 Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:3000/node_modules/ng2-select2/src/select2.component
Error: XHR error (404 Not Found) loading http://localhost:3000/node_modules/ng2-select2/src/select2.component
at XMLHttpRequest.wrapFn [as _onreadystatechange] (http://localhost:3000/node_modules/zone.js/dist/zone.js:851:29) []
at Zone.runTask (http://localhost:3000/node_modules/zone.js/dist/zone.js:151:47) [ => ]
but when i add : 'ng2-select2': 'npm:ng2-select2/ng2-select2.js', to sytem.config.js i get ng2-select.component not found.
Hey trying to see how this is working. Kinda made difficult because the demo and plunkr are out of date.
The Select2Component should provide a function which helps to select the specified element of the list.
I've binded select2
directive to a component field plans
:
<select2 id="default-select"
(valueChanged)="select2Changed($event)"
[data]="plans" <<<<<<<<<<<<<<<<
[width]="250"
[theme]="'bootstrap'">
</select2>
I'm populating plans
field using Rxjs:
export class Signin implements OnInit {
private plans: Array<Select2OptionData>;
constructor() {
this.plans = [];
}
ngOnInit():void {
this.serverService
.list()
.subscribe(
(result: any) => {
this.plans.splice(0, this.plans.length);
for (let plan of result)
this.plans.push({id: plan.id, text: plan.name});
},
(error: any) => {
}
);
}
}
Nevertheless, select2
is not populated. I've debugged data is well received and pushed on on plans
field.
Should I take in mind any issue?
According to this this, a value = null
should clear selection.
Here is an example so you can see the strange behavior.
http://plnkr.co/edit/XHJqJu?p=preview&open=app%2Fapp.component.ts
compile cannot find Select2TemplateFunction in app.ts?
hi Guys,
Is it possible to pass dynamic data to the select?
Because I am trying to get data from rxjs observable and trying to bind it to the [data] but its not taking?
(Its only taking static data in my case)
Is it possible to bind data to the select2 element which is result of http call?
Hello,
I'm getting the following message in console when loading your select component:
"Please add Select2 library (js file) to the project. You can download it from https://github.com/select2/select2/tree/master/dist/js."
I did everything for the installation..
Installed Jquery & Select2 and added it to my angular-cli.json:
"scripts": [ "../node_modules/jquery/dist/jquery.js", "../node_modules/select2/dist/js/select2.full.js" ]
Installed ng2-select2 via npm
Added ng2-select2 to my NgModule imports of my template where I added my select2 component.
module:
import {Select2Module} from "ng2-select2";
@NgModule({ declarations: [ RegisterCompanyComponent ], imports: [ CommonModule, FormsModule, ReactiveFormsModule, Select2Module, RouterModule.forChild(routes), ] })
html:
<select2 [data]="countries" [width]="150"></select2>
If I look at the scripts.bundle.js in my browsers source, the select2 library is in there:
module.exports = "/*!\r\n * Select2 4.0.3\r\n * https://select2.github.io\r\n
Here are the versions I use:
I hope you can help me..
Using [email protected] I found that allowClear: true
option allows to clear selection in the UI, but the valueChanged
event is firing incorrectly with the value of the last selected option instead of an empty one.
I'm getting this message from angular2:
EXCEPTION: Uncaught (in promise): Error: Error in ./Signin class Signin - inline template:59:20 caused by: this.element.select2 is not a function
["./node_modules/ng2-select2/src/select2.component.js"]/</Select2Component</Select2Component.prototype.ngAfterViewInit@http://localhost:3002/1.chunk.js:20408:13
anonymous/View_Signin0.prototype.detectChangesInternal@/SigninModule/Signin/component.ngfactory.js:771:40
ac_vendor<["./node_modules/@angular/core/src/linker/view.js"]/AppView</AppView.prototype.detectChanges@http://localhost:3002/vendor.bundle.js:49160:9
ac_vendor<["./node_modules/@angular/core/src/linker/view.js"]/DebugAppView</DebugAppView.prototype.detectChanges@http://localhost:3002/vendor.bundle.js:49355:13
anonymous/View_Signin_Host0.prototype.detectChangesInternal@/SigninModule/Signin/host.ngfactory.js:36:3
ac_vendor<["./node_modules/@angular/core/src/linker/view.js"]/AppView</AppView.prototype.detectChanges@http://localhost:3002/vendor.bundle.js:49160:9
ac_vendor<["./node_mod[…]
I've added dependencies on my compoenent and module:
Module:
import { AlertModule } from 'ng2-bootstrap/ng2-bootstrap';
import { Select2Module } from 'ng2-select2';
@NgModule({
declarations: [
Signin
],
imports: [
CommonModule,
ReactiveFormsModule,
AlertModule,
Select2Module,
RouterModule.forChild(routes),
]
})
export default class SigninModule {
static routes = routes;
}
Component:
import { Select2OptionData } from 'ng2-select2';
declare var jQuery: any;
@Component(...)
export class Signin implements OnInit {
private plans: Array<Select2OptionData>;
constructor()
{
this.alerts = [];
this.plans = [];
}
ngOnInit():void {
this.form = this.fb.group({
mail: ['', Validators.required],
passwd: ['', Validators.minLength(6)],
passwdConfirm: ['', Validators.minLength(6)],
cname: ['', Validators.required],
sname: ['']
});
var p = jQuery('.parsleyjs').parsley();
this.plans = [{
id: 'Magellanic',
text: 'Large Magellanic Cloud'
},
{
id: 'Andromeda',
text: 'Andromeda Galaxy'
},
{
id: 'Sextans',
text: 'Sextans A'
}];
}
select2Changed(e: any): void {
this.selected = e.value;
}
getSelect2DefaultList(): Array<Select2OptionData> {
return this.plans;
}
My template is using select2
directive as:
<select2 id="default-select"
(valueChanged)="select2Changed($event)"
[data]="getSelect2DefaultList()" [width]="250" [theme]="'bootstrap'"></select2>
Any ideas?
Instead of passing each option separately, we pass all options trough one input. The only other input that should be there is data input.
Trying to get this working for my project but for some reason the search box isn't editable/accessible. I can select a value from the dropdown which then populates the field correctly, but I'm unable to type anything into the search box.
The code I'm using for my searchbox (very basic):
<select2 [data]="[{id: 'val1', text: 'Value 1'},{id: 'val2', text: 'Value 2'}]"></select2>
hi,
We are installing [email protected] because it's a dependency of [email protected] template
we are using @angular/[email protected]
The "npm install" and "npm ls" commands prints "[email protected] invalid"
if the ng2-select2 package meets angular dependency, why it's being reported as "invalid"?
Thank you
I cloned the demo
branch, run nmp install
and then ng serve
and this error occurred:
ERROR in Select2Module is not an NgModule
webpack: Failed to compile.
Hi,
Select2 supports server side pagination, have you implemented that as well?
Thanks
Hi,
I have another suggestion to improve your great component !
Unless I'm mistaken, there is no way to disable the field : option [disabled]="isDisabled" does not work => Can't bind to 'disabled' since it isn't a known property of 'select2'.
Good luck :D
Quentin
I need to display initial values as selected on a multiple select input.
In order to achieve this I've tried passing an array to [value]. When the initial values array has only one value (always of type string), the option is displayed as selected. However, when the initial values array has 2 or more values, nothing is displayed as selected.
Is there a way I can work around this issue?
This would be good to have a support for the standard Form / ngModel.
Browser: Chrome
Console output:
run.plnkr.co/:1 XMLHttpRequest cannot load https://npmcdn.com/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://run.plnkr.co' is therefore not allowed access.
zone.js:323 Error: (SystemJS) Error: XHR error loading https://npmcdn.com/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js(…)ZoneDelegate.invoke @ zone.js:323Zone.run @ zone.js:216(anonymous function) @ zone.js:571ZoneDelegate.invokeTask @ zone.js:356Zone.runTask @ zone.js:256drainMicroTaskQueue @ zone.js:474ZoneTask.invoke @ zone.js:426
run.plnkr.co/:1 XMLHttpRequest cannot load https://npmcdn.com/@angular/core/bundles/core.umd.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://run.plnkr.co' is therefore not allowed access.
run.plnkr.co/:1 XMLHttpRequest cannot load https://npmcdn.com/@angular/platform-browser/bundles/platform-browser.umd.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://run.plnkr.co' is therefore not allowed access.
run.plnkr.co/:1 XMLHttpRequest cannot load https://npmcdn.com/[email protected]//ng2-select2.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://run.plnkr.co' is therefore not allowed access.
The TypeScript compiler is unable to locate your type definitions automatically. Would you mind adding "typings": "dist/ng2-select2.d.ts"
to your package.json? See https://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html.
Hi !
I'm currently meeting a problem with your solution...
I can only select a value dynamically once. When I change the data list, I cannot....
Could you take a look for that problem please ?
Your solution is really great, but this is missing.
Quentin
The original select2 can work with <option>
tags below it. Example:
<select id="foo">
<option value="1">First option</option>
<option value="2">Second option</option>
</select>
And then turn it into a select2 control:
$("#optimize").select2({ minimumResultsForSearch: -1 });
I think this control should support the same markup:
<select2 id="foo">
<option value="1">First option</option>
<option value="2">Second option</option>
</select2>
It could be easily done using <ng-content></ng-content>
.
Versions:
Angular 2: 2.4.1
JQuery: 3.1.1
Select2: 4.0.3
Ng-Select2: 1.0.0-beta.7
Template Code:
<select2 class="form-control"
[options]="options"
[data]="data"
(valueChanged)="valueChanged($event)">
</select2>
or
<select2 class="form-control"
[options]="options"
[data]="data$ | async"
(valueChanged)="valueChanged($event)">
</select2>
Component Code:
ngOnInit() {
this.data = [{ id: 1, text: 'test'}];
}
or
ngOnInit() {
this.data$.next([{ id: 1, text: 'test'}]);
}
In both cases valueChanged is fired when the list data is bound to [data]. This is particularly detrimental to my use case in which I'm using the selected value for flow control purposes.
and why you provide them into the component
If you are using custom matcher, value is not set correctly.
Found here: UltimateHackingKeyboard/agent#230
Hi,
Would be possible to put it as a Module? It's in order to be importable from App Module and use AoT compilation at the same time.
Thanks in advance.
Hi, I've tried to implement ajax data loading and it fails saying
TypeError: c.ajax is not a function
Searched for that error in Google and there's anything about it. Here is my component
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-select2item',
templateUrl: './select2item.component.html',
styleUrls: ['./select2item.component.css']
})
export class Select2itemComponent implements OnInit {
private select2options:S2options;
constructor() { }
ngOnInit() {
this.select2options = {};
this.select2options.ajax={
url:"/item/ajax",
dataType: 'json',
data: (term)=>{ return {sku:term} }
};
}
}
interface S2options{
ajax?:Select2AjaxOptions;
}
interface Select2AjaxOptions {
transport?: AjaxFunction;
url?: any;
dataType?: string;
delay?: number;
cache?: boolean;
data?: (term: string, page: number, context: any) => any;
results?: (term: any, page: number, context: any) => any;
processResults?:(data: any, params: any) => any;
}
interface AjaxFunction {
(settings: JQueryAjaxSettings): JQueryXHR;
(url: string, settings?: JQueryAjaxSettings): JQueryXHR;
}
Don't know if there's something wrong, I am a newbie with Angular
Hi,
Trying to find my way around this library. Is there an example of how to create a multiple select dropdown?
Thanks
Tam
I want to add some style such as width, height, border-radius, font-weight, font-size, ... but I couldn't manage it. Is there any way to do it?
I have installed the package and followed the plunker example but it is not working.
I have created an issue with code. Please have a look.
Can someone please tell me how I can change the style?
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.