seperate ng-select into a ng-select lib

This commit is contained in:
Yubing325 2020-07-06 12:21:52 -05:00
parent 58f2ec48d0
commit 420c2c18b6
25 changed files with 450 additions and 26 deletions

View File

@ -204,6 +204,46 @@
} }
} }
} }
},
"@poweredsoft/ng-select": {
"projectType": "library",
"root": "projects/poweredsoft/ng-select",
"sourceRoot": "projects/poweredsoft/ng-select/src",
"prefix": "ps-ng",
"architect": {
"build": {
"builder": "@angular-devkit/build-ng-packagr:build",
"options": {
"tsConfig": "projects/poweredsoft/ng-select/tsconfig.lib.json",
"project": "projects/poweredsoft/ng-select/ng-package.json"
},
"configurations": {
"production": {
"tsConfig": "projects/poweredsoft/ng-select/tsconfig.lib.prod.json"
}
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "projects/poweredsoft/ng-select/src/test.ts",
"tsConfig": "projects/poweredsoft/ng-select/tsconfig.spec.json",
"karmaConfig": "projects/poweredsoft/ng-select/karma.conf.js"
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"projects/poweredsoft/ng-select/tsconfig.lib.json",
"projects/poweredsoft/ng-select/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
}}, }},
"defaultProject": "ngx-cdk-ui" "defaultProject": "ngx-cdk-ui"
} }

View File

@ -0,0 +1,24 @@
# NgSelect
This library was generated with [Angular CLI](https://github.com/angular/angular-cli) version 9.1.9.
## Code scaffolding
Run `ng generate component component-name --project ng-select` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module --project ng-select`.
> Note: Don't forget to add `--project ng-select` or else it will be added to the default project in your `angular.json` file.
## Build
Run `ng build ng-select` to build the project. The build artifacts will be stored in the `dist/` directory.
## Publishing
After building your library with `ng build ng-select`, go to the dist folder `cd dist/ng-select` and run `npm publish`.
## Running unit tests
Run `ng test ng-select` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).

View File

@ -0,0 +1,32 @@
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, '../../../coverage/poweredsoft/ng-select'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};

View File

@ -0,0 +1,7 @@
{
"$schema": "../../../node_modules/ng-packagr/ng-package.schema.json",
"dest": "../../../dist/poweredsoft/ng-select",
"lib": {
"entryFile": "src/public-api.ts"
}
}

View File

@ -0,0 +1,11 @@
{
"name": "@poweredsoft/ng-select",
"version": "0.0.1",
"peerDependencies": {
"@angular/common": "^9.1.9",
"@angular/core": "^9.1.9"
},
"dependencies": {
"tslib": "^1.10.0"
}
}

View File

@ -0,0 +1 @@
<p>multi-select works!</p>

View File

@ -0,0 +1,15 @@
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'ps-ng-multi-select',
templateUrl: './multi-select.component.html',
styleUrls: ['./multi-select.component.scss']
})
export class MultiSelectComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}

View File

@ -0,0 +1,17 @@
<ng-select [items]="data$ |async"
[bindLabel]="bindLabel"
[bindValue]="bindValue"
autofocus
[typeahead] = "searchInput$"
[trackByFn]="trackFn"
(change)="valueChanged($event)">
<ng-container *ngIf="hasOptionTemplate">
<ng-template ng-option-tmp let-item="item" let-index="index">
<ng-container [ngTemplateOutlet]="selectOptionTemplate"
[ngTemplateOutletContext]="{
$implicit: item,
index: index
}"></ng-container>
</ng-template>
</ng-container>
</ng-select>

View File

@ -0,0 +1,143 @@
import { Component, OnInit, ContentChild, ViewChild, Input, Output, EventEmitter, ChangeDetectorRef, forwardRef } from '@angular/core';
import { SelectLabelTemplateDirective } from '../select-label-template.directive';
import { IDataSource, ISimpleFilter } from '@poweredsoft/data';
import { Observable, Subject, Subscription } from 'rxjs';
import { map, distinctUntilChanged, debounceTime } from 'rxjs/operators';
import { NgSelectComponent as SelectComponent } from '@ng-select/ng-select';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'ps-ng-select',
templateUrl: './ng-select.component.html',
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => NgSelectComponent),
multi: true
}],
styleUrls: ['./ng-select.component.scss']
})
export class NgSelectComponent implements OnInit {
@ContentChild(SelectLabelTemplateDirective) LabelTemplate: SelectLabelTemplateDirective;
@ViewChild(SelectComponent, { static: true }) selectComponent: SelectComponent;
@Input() dataSource: IDataSource<any>;
@Input() searchPath: string;
@Input() searchType: string;
@Input() sortingPath: string;
@Input() serverFiltering:boolean;
@Input() bindLabel:string;
@Input() bindValue: string;
@Output('change') changeEvent = new EventEmitter();
trackFn: (item: any) => any;
data$ : Observable<any[]>;
isLoading:boolean = false;
searchInput$ = new Subject<string>();
private _loadingSubscription: Subscription;
constructor(private cdr: ChangeDetectorRef) {
this.trackFn = this.trackBy.bind(this);
}
valueChanged(event) {
this.changeEvent.emit(event);
}
writeValue(obj: any): void {
this.selectComponent.writeValue(obj);
}
registerOnChange(fn: any): void {
this.selectComponent.registerOnChange(fn);
}
registerOnTouched(fn: any): void {
this.selectComponent.registerOnTouched(fn);
}
setDisabledState?(isDisabled: boolean): void {
if (this.selectComponent.setDisabledState)
this.selectComponent.setDisabledState(isDisabled);
}
trackBy(item: any) {
return this.dataSource.resolveIdField(item);
}
ngOnDestroy(): void {
this._loadingSubscription.unsubscribe();
}
ngOnInit(): void {
this.dataFetching();
this.detectLoading();
console.log(this.serverFiltering);
if(this.serverFiltering){
this.searchOnServer();
}else{
this.refreshDataSource();
}
}
dataFetching(){
this.data$ = this.dataSource.data$.pipe(
map(t => {
if (t == null)
return [];
return t.data;
})
);
}
detectLoading(){
this._loadingSubscription = this.dataSource.loading$.subscribe(loading => {
this.isLoading = loading;
this.cdr.detectChanges();
});
}
searchOnServer(){
this.searchInput$.pipe(
distinctUntilChanged(), // emit the difference from previous input
debounceTime(500) // this is for delaying searching speed
).subscribe(searchTerm => this.refreshDataSource(searchTerm, 1, 100)); // page: 1, pageSize: 50
this.refreshDataSource(); //send the query to server to sorting & filtering by default
}
get selectedModel() {
return this.selectComponent.hasValue ? this.selectComponent.selectedItems[0].value : null;
}
refreshDataSource(searchTerm:any = null, page:number = null, pageSize:number = null){
let searchfilters:ISimpleFilter[] = null;
if(searchTerm){
searchfilters = [<ISimpleFilter>{
path: this.searchPath || this.bindLabel,
type: this.searchType || 'Contains', // Default: Contains
value: searchTerm
}]
}
this.dataSource.query({
page: page,
pageSize: pageSize,
filters:searchfilters,
sorts:[
{path: this.sortingPath || this.bindLabel, ascending: true}
]
})
}
get hasOptionTemplate() {
return this.LabelTemplate ? true : false;
}
get selectOptionTemplate(){
if (this.LabelTemplate)
return this.LabelTemplate.template;
return null;
}
}

View File

@ -0,0 +1,24 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NgSelectComponent } from './ng-select/ng-select.component';
import { MultiSelectComponent } from './multi-select/multi-select.component';
import { FormsModule } from '@angular/forms';
import { NgSelectModule } from '@ng-select/ng-select';
import { SelectLabelTemplateDirective } from './select-label-template.directive';
@NgModule({
declarations: [NgSelectComponent, MultiSelectComponent, SelectLabelTemplateDirective],
imports: [
CommonModule,
FormsModule,
NgSelectModule,
],
exports:[
NgSelectComponent,
MultiSelectComponent,
SelectLabelTemplateDirective
]
})
export class PsNgSelectorsModule { }

View File

@ -0,0 +1,8 @@
import { SelectLabelTemplateDirective } from './select-label-template.directive';
describe('SelectLabelTemplateDirective', () => {
it('should create an instance', () => {
const directive = new SelectLabelTemplateDirective();
expect(directive).toBeTruthy();
});
});

View File

@ -0,0 +1,10 @@
import { Directive, TemplateRef } from '@angular/core';
@Directive({
selector: '[psNgSelectLabel]'
})
export class SelectLabelTemplateDirective {
constructor(public template: TemplateRef<any>) { }
}

View File

@ -0,0 +1,11 @@
/*
* Public API Surface of ng-select
*/
export * from './lib/ps-ng-selectors/ps-ng-selectors.module';
export * from './lib/ps-ng-selectors/ng-select/ng-select.component';
export * from './lib/ps-ng-selectors/multi-select/multi-select.component';
export * from './lib/ps-ng-selectors/select-label-template.directive';

View File

@ -0,0 +1,26 @@
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/zone';
import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
declare const require: {
context(path: string, deep?: boolean, filter?: RegExp): {
keys(): string[];
<T>(id: string): T;
};
};
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);

View File

@ -0,0 +1,23 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "../../../out-tsc/lib",
"target": "es2015",
"declaration": true,
"inlineSources": true,
"types": [],
"lib": [
"dom",
"es2018"
]
},
"angularCompilerOptions": {
"skipTemplateCodegen": true,
"strictMetadataEmit": true,
"enableResourceInlining": true
},
"exclude": [
"src/test.ts",
"**/*.spec.ts"
]
}

View File

@ -0,0 +1,6 @@
{
"extends": "./tsconfig.lib.json",
"angularCompilerOptions": {
"enableIvy": false
}
}

View File

@ -0,0 +1,17 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "../../../out-tsc/spec",
"types": [
"jasmine",
"node"
]
},
"files": [
"src/test.ts"
],
"include": [
"**/*.spec.ts",
"**/*.d.ts"
]
}

View File

@ -0,0 +1,17 @@
{
"extends": "../../../tslint.json",
"rules": {
"directive-selector": [
true,
"attribute",
"lib",
"camelCase"
],
"component-selector": [
true,
"element",
"lib",
"kebab-case"
]
}
}

View File

@ -1,17 +0,0 @@
<ng-select [items]="data$ |async"
[bindLabel]="bindLabel"
[bindValue]="bindValue"
autofocus
[typeahead] = "searchInput$"
[trackByFn]="trackFn"
(change)="valueChanged($event)">
<ng-container *ngIf="hasOptionTemplate">
<ng-template ng-option-tmp let-item="item" let-index="index">
<ng-container [ngTemplateOutlet]="selectOptionTemplate"
[ngTemplateOutletContext]="{
$implicit: item,
index: index
}"></ng-container>
</ng-template>
</ng-container>
</ng-select>

View File

@ -12,6 +12,7 @@ import { InMemoryCache } from 'apollo-cache-inmemory';
import { HttpClientModule } from '@angular/common/http'; import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
export function app_Init(apollo: Apollo, httpLink: HttpLink) { export function app_Init(apollo: Apollo, httpLink: HttpLink) {
return async () => { return async () => {
const defaultOptions: DefaultOptions = { const defaultOptions: DefaultOptions = {
@ -50,6 +51,7 @@ export function app_Init(apollo: Apollo, httpLink: HttpLink) {
declarations: [ declarations: [
AppComponent, AppComponent,
HomeComponent, HomeComponent,
//SelectLabelTemplateDirective,
], ],
imports: [ imports: [

View File

@ -4,7 +4,8 @@ import { NgSelectDemoComponent } from './ng-select-demo/ng-select-demo.component
import { NgSelectDemoRoutingModule } from './ng-select-demo-routing.module'; import { NgSelectDemoRoutingModule } from './ng-select-demo-routing.module';
import { NgSelectModule } from '@ng-select/ng-select'; import { NgSelectModule } from '@ng-select/ng-select';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { PsSelectorsModule } from '@poweredsoft/ngx-cdk-ui'; import { PsNgSelectorsModule } from '@poweredsoft/ng-select';
@ -16,7 +17,7 @@ import { PsSelectorsModule } from '@poweredsoft/ngx-cdk-ui';
FormsModule, FormsModule,
ReactiveFormsModule, ReactiveFormsModule,
NgSelectDemoRoutingModule, NgSelectDemoRoutingModule,
PsSelectorsModule //our ng select module PsNgSelectorsModule
] ]
}) })
export class NgSelectDemoModule { } export class NgSelectDemoModule { }

View File

@ -1,25 +1,27 @@
<h2>Single Select Demo</h2> <h2>Single Select Demo</h2>
<ps-ng-select [dataSource]="merchantDataSource" bindLabel="name" bindValue="id" [serverFiltering]="true"> <ps-ng-select [dataSource]="merchantDataSource" bindLabel="name" bindValue="id" [serverFiltering]="true">
<div *psSelectOptionTemplate="let item"> <div *psNgSelectLabel="let item">
{{ item.name }} - {{ item.address }} {{ item.name }} - {{ item.address }}
</div> </div>
</ps-ng-select> </ps-ng-select>
<h2>Multi-Select Demo</h2> <!-- <h2>Multi-Select Demo</h2>
<ps-ng-multi-select [dataSource]="merchantDataSource" [searchPath]="'name'" [sortingPath]="'name'" [disableServer]="false" [bindLabel]="'name'"></ps-ng-multi-select> <ps-ng-multi-select [dataSource]="merchantDataSource" [searchPath]="'name'" [sortingPath]="'name'" [disableServer]="false" [bindLabel]="'name'"></ps-ng-multi-select> -->
<!-- <form> <!-- <form>
<ps-ng-select [dataSource]="merchantDataSource" searchPath="name" sortingPath="name" formControlName="name" [disableServer]="false" bindLabel="name"> <ps-ng-select [dataSource]="merchantDataSource" searchPath="name" sortingPath="name" formControlName="name" [disableServer]="false" bindLabel="name">
<ng-template *psSelectOptionTemplate="let item" ng-label-tmp > <ng-template *psNgSelectLabel="let item" ng-label-tmp >
<span>Name: </span> {{item.name}} | <span>Adress: </span>{{item.address}} | <span>Date: </span>{{item.openDate}} <span>Name: </span> {{item.name}} | <span>Adress: </span>{{item.address}} | <span>Date: </span>{{item.openDate}}
</ng-template> </ng-template>
</ps-ng-select> </ps-ng-select>
</form> --> </form> -->
<!--
<form #form [formGroup]="myForm"> <form #form [formGroup]="myForm">
<ps-ng-select [dataSource]="merchantDataSource" bindLabel="name" bindValue="id" formControlName="merchantId"> <ps-ng-select [dataSource]="merchantDataSource" bindLabel="name" bindValue="id" formControlName="merchantId">
<div *psSelectOptionTemplate="let item"> <div *psNgSelectLabel="let item">
{{ item.name }} - {{ item.address }} {{ item.name }} - {{ item.address }}
</div> </div>
</ps-ng-select> </ps-ng-select>
@ -29,9 +31,9 @@
<ps-ng-select [dataSource]="merchantDataSource" bindLabel="name" bindValue="id" [(ngModel)]="myValue"> <ps-ng-select [dataSource]="merchantDataSource" bindLabel="name" bindValue="id" [(ngModel)]="myValue">
<div *psSelectOptionTemplate="let item"> <div *psNgSelectLabel="let item">
{{ item.name }} - {{ item.address }} {{ item.name }} - {{ item.address }}
</div> </div>
</ps-ng-select> </ps-ng-select>
{{ myValue | json }} {{ myValue | json }} -->

View File

@ -23,6 +23,10 @@
"@poweredsoft/ngx-bootstrap": [ "@poweredsoft/ngx-bootstrap": [
"dist/poweredsoft/ngx-bootstrap/poweredsoft-ngx-bootstrap", "dist/poweredsoft/ngx-bootstrap/poweredsoft-ngx-bootstrap",
"dist/poweredsoft/ngx-bootstrap" "dist/poweredsoft/ngx-bootstrap"
],
"@poweredsoft/ng-select": [
"dist/poweredsoft/ng-select/poweredsoft-ng-select",
"dist/poweredsoft/ng-select"
] ]
} }
}, },