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
+24
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).
@@ -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
});
};
@@ -0,0 +1,7 @@
{
"$schema": "../../../node_modules/ng-packagr/ng-package.schema.json",
"dest": "../../../dist/poweredsoft/ng-select",
"lib": {
"entryFile": "src/public-api.ts"
}
}
@@ -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"
}
}
@@ -0,0 +1 @@
<p>multi-select works!</p>
@@ -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 {
}
}
@@ -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>
@@ -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;
}
}
@@ -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 { }
@@ -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();
});
});
@@ -0,0 +1,10 @@
import { Directive, TemplateRef } from '@angular/core';
@Directive({
selector: '[psNgSelectLabel]'
})
export class SelectLabelTemplateDirective {
constructor(public template: TemplateRef<any>) { }
}
@@ -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';
@@ -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);
@@ -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"
]
}
@@ -0,0 +1,6 @@
{
"extends": "./tsconfig.lib.json",
"angularCompilerOptions": {
"enableIvy": false
}
}
@@ -0,0 +1,17 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"outDir": "../../../out-tsc/spec",
"types": [
"jasmine",
"node"
]
},
"files": [
"src/test.ts"
],
"include": [
"**/*.spec.ts",
"**/*.d.ts"
]
}
@@ -0,0 +1,17 @@
{
"extends": "../../../tslint.json",
"rules": {
"directive-selector": [
true,
"attribute",
"lib",
"camelCase"
],
"component-selector": [
true,
"element",
"lib",
"kebab-case"
]
}
}
@@ -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>