Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding support for custom properties in object options - issue#172 #377

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions src/app/components/select/multiple-demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ export class MultipleDemoComponent implements OnInit {

ngOnInit() {
this.cities = [
{ item_id: 1, item_text: 'New Delhi' },
{ item_id: 2, item_text: 'Mumbai' },
{ item_id: 3, item_text: 'Bangalore' },
{ item_id: 1, item_text: 'New Delhi', population: 1_173_902 },
{ item_id: 2, item_text: 'Mumbai', timezone: 'India Standard Time' },
{ item_id: 3, item_text: 'Bangalore', isDisabled: this.disableBangalore },
{ item_id: 4, item_text: 'Pune' },
{ item_id: 5, item_text: 'Chennai' },
{ item_id: 6, item_text: 'Navsari' }
Expand Down Expand Up @@ -112,8 +112,8 @@ export class MultipleDemoComponent implements OnInit {

ngOnInit() {
this.cities = [
{ item_id: 1, item_text: 'New Delhi' },
{ item_id: 2, item_text: 'Mumbai' },
{ item_id: 1, item_text: 'New Delhi', population: 1_173_902 },
{ item_id: 2, item_text: 'Mumbai', timezone: 'India Standard Time' },
{ item_id: 3, item_text: 'Bangalore', isDisabled: this.disableBangalore },
{ item_id: 4, item_text: 'Pune' },
{ item_id: 5, item_text: 'Chennai' },
Expand Down Expand Up @@ -191,7 +191,6 @@ export class MultipleDemoComponent implements OnInit {
itemsShowLimit: 999999
});
}
console.log()
}


Expand Down
105 changes: 58 additions & 47 deletions src/ng-multiselect-dropdown/src/multiselect.component.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import { Component, HostListener, forwardRef, Input, Output, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef } from "@angular/core";
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from "@angular/forms";
import { ListItem, IDropdownSettings } from "./multiselect.model";
import { ListFilterPipe } from "./list-filter.pipe";
import {Component, HostListener, forwardRef, Input, Output, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These were automatic formatting changes made by the linter, let me know if you need them reverted.

import {NG_VALUE_ACCESSOR, ControlValueAccessor} from '@angular/forms';
import {ListItem, IDropdownSettings} from './multiselect.model';
import {ListFilterPipe} from './list-filter.pipe';

export const DROPDOWN_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MultiSelectComponent),
multi: true
};
const noop = () => {};
const noop = () => {
};

@Component({
selector: "ng-multiselect-dropdown",
templateUrl: "./multi-select.component.html",
styleUrls: ["./multi-select.component.scss"],
selector: 'ng-multiselect-dropdown',
templateUrl: './multi-select.component.html',
styleUrls: ['./multi-select.component.scss'],
providers: [DROPDOWN_CONTROL_VALUE_ACCESSOR],
changeDetection: ChangeDetectionStrategy.OnPush
})
Expand All @@ -22,26 +23,26 @@ export class MultiSelectComponent implements ControlValueAccessor {
public _data: Array<ListItem> = [];
public selectedItems: Array<ListItem> = [];
public isDropdownOpen = true;
_placeholder = "Select";
_placeholder = 'Select';
private _sourceDataType = null; // to keep note of the source data type. could be array of string/number/object
private _sourceDataFields: Array<String> = []; // store source data fields names
filter: ListItem = new ListItem(this.data);
defaultSettings: IDropdownSettings = {
singleSelection: false,
idField: "id",
textField: "text",
disabledField: "isDisabled",
idField: 'id',
textField: 'text',
disabledField: 'isDisabled',
enableCheckAll: true,
selectAllText: "Select All",
unSelectAllText: "UnSelect All",
selectAllText: 'Select All',
unSelectAllText: 'UnSelect All',
allowSearchFilter: false,
limitSelection: -1,
clearSearchFilter: true,
maxHeight: 197,
itemsShowLimit: 999999999999,
searchPlaceholderText: "Search",
noDataAvailablePlaceholderText: "No data available",
noFilteredDataAvailablePlaceholderText: "No filtered data available",
searchPlaceholderText: 'Search',
noDataAvailablePlaceholderText: 'No data available',
noFilteredDataAvailablePlaceholderText: 'No filtered data available',
closeDropDownOnSelection: false,
showSelectedItemsAtTop: false,
defaultOpen: false,
Expand All @@ -53,9 +54,10 @@ export class MultiSelectComponent implements ControlValueAccessor {
if (value) {
this._placeholder = value;
} else {
this._placeholder = "Select";
this._placeholder = 'Select';
}
}

@Input()
disabled = false;

Expand All @@ -76,33 +78,35 @@ export class MultiSelectComponent implements ControlValueAccessor {
const firstItem = value[0];
this._sourceDataType = typeof firstItem;
this._sourceDataFields = this.getFields(firstItem);

this._data = value.map((item: any) =>
typeof item === "string" || typeof item === "number"
typeof item === 'string' || typeof item === 'number'
? new ListItem(item)
: new ListItem({
id: item[this._settings.idField],
text: item[this._settings.textField],
isDisabled: item[this._settings.disabledField]
})
);
id: item[this._settings.idField],
text: item[this._settings.textField],
sourceObj: Object.assign({}, this.getSourceObj(item)), // keep other object props
isDisabled: item[this._settings.disabledField]
})
);
}
}

@Output("onFilterChange")
@Output('onFilterChange')
onFilterChange: EventEmitter<ListItem> = new EventEmitter<any>();
@Output("onDropDownClose")
@Output('onDropDownClose')
onDropDownClose: EventEmitter<ListItem> = new EventEmitter<any>();

@Output("onSelect")
@Output('onSelect')
onSelect: EventEmitter<ListItem> = new EventEmitter<any>();

@Output("onDeSelect")
@Output('onDeSelect')
onDeSelect: EventEmitter<ListItem> = new EventEmitter<any>();

@Output("onSelectAll")
@Output('onSelectAll')
onSelectAll: EventEmitter<Array<ListItem>> = new EventEmitter<Array<any>>();

@Output("onDeSelectAll")
@Output('onDeSelectAll')
onDeSelectAll: EventEmitter<Array<ListItem>> = new EventEmitter<Array<any>>();

private onTouchedCallback: () => void = noop;
Expand All @@ -113,7 +117,7 @@ export class MultiSelectComponent implements ControlValueAccessor {
}

constructor(
private listFilterPipe:ListFilterPipe,
private listFilterPipe: ListFilterPipe,
private cdr: ChangeDetectorRef
) {}

Expand Down Expand Up @@ -143,27 +147,27 @@ export class MultiSelectComponent implements ControlValueAccessor {
if (value.length >= 1) {
const firstItem = value[0];
this.selectedItems = [
typeof firstItem === "string" || typeof firstItem === "number"
typeof firstItem === 'string' || typeof firstItem === 'number'
? new ListItem(firstItem)
: new ListItem({
id: firstItem[this._settings.idField],
text: firstItem[this._settings.textField],
isDisabled: firstItem[this._settings.disabledField]
})
id: firstItem[this._settings.idField],
text: firstItem[this._settings.textField],
isDisabled: firstItem[this._settings.disabledField]
})
];
}
} catch (e) {
// console.error(e.body.msg);
}
} else {
const _data = value.map((item: any) =>
typeof item === "string" || typeof item === "number"
typeof item === 'string' || typeof item === 'number'
? new ListItem(item)
: new ListItem({
id: item[this._settings.idField],
text: item[this._settings.textField],
isDisabled: item[this._settings.disabledField]
})
id: item[this._settings.idField],
text: item[this._settings.textField],
isDisabled: item[this._settings.disabledField]
})
);
if (this._settings.limitSelection > 0) {
this.selectedItems = _data.splice(0, this._settings.limitSelection);
Expand All @@ -190,7 +194,7 @@ export class MultiSelectComponent implements ControlValueAccessor {
}

// Set touched on blur
@HostListener("blur")
@HostListener('blur')
public onTouched() {
// this.closeDropdown();
this.onTouchedCallback();
Expand All @@ -216,7 +220,7 @@ export class MultiSelectComponent implements ControlValueAccessor {

isAllItemsSelected(): boolean {
// get disabld item count
let filteredItems = this.listFilterPipe.transform(this._data,this.filter);
let filteredItems = this.listFilterPipe.transform(this._data, this.filter);
const itemDisabledCount = filteredItems.filter(item => item.isDisabled).length;
// take disabled items into consideration when checking
if ((!this.data || this.data.length === 0) && this._settings.allowRemoteDataSearch) {
Expand Down Expand Up @@ -279,7 +283,7 @@ export class MultiSelectComponent implements ControlValueAccessor {

objectify(val: ListItem) {
if (this._sourceDataType === 'object') {
const obj = {};
const obj = Object.assign({}, val.sourceObj);
obj[this._settings.idField] = val.id;
obj[this._settings.textField] = val.text;
if (this._sourceDataFields.includes(this._settings.disabledField)) {
Expand Down Expand Up @@ -309,7 +313,7 @@ export class MultiSelectComponent implements ControlValueAccessor {
this._settings.defaultOpen = false;
// clear search text
if (this._settings.clearSearchFilter) {
this.filter.text = "";
this.filter.text = '';
}
this.onDropDownClose.emit();
}
Expand All @@ -320,7 +324,7 @@ export class MultiSelectComponent implements ControlValueAccessor {
}
if (!this.isAllItemsSelected()) {
// filter out disabled item first before slicing
this.selectedItems = this.listFilterPipe.transform(this._data,this.filter).filter(item => !item.isDisabled).slice();
this.selectedItems = this.listFilterPipe.transform(this._data, this.filter).filter(item => !item.isDisabled).slice();
this.onSelectAll.emit(this.emittedValue(this.selectedItems));
} else {
this.selectedItems = [];
Expand All @@ -331,7 +335,7 @@ export class MultiSelectComponent implements ControlValueAccessor {

getFields(inputData) {
const fields = [];
if (typeof inputData !== "object") {
if (typeof inputData !== 'object') {
return fields;
}
// tslint:disable-next-line:forin
Expand All @@ -341,4 +345,11 @@ export class MultiSelectComponent implements ControlValueAccessor {
return fields;
}

getSourceObj(value: {}) {
const omitProps = [this._settings.idField, this._settings.textField, this._settings.disabledField];
const obj = Object.assign({}, value);
omitProps.forEach(prop => delete obj[prop]);
return obj;
}

}
2 changes: 2 additions & 0 deletions src/ng-multiselect-dropdown/src/multiselect.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export class ListItem {
id: String | number;
text: String | number;
isDisabled?: boolean;
sourceObj?: {} | undefined;

public constructor(source: any) {
if (typeof source === 'string' || typeof source === 'number') {
Expand All @@ -33,6 +34,7 @@ export class ListItem {
if (typeof source === 'object') {
this.id = source.id;
this.text = source.text;
this.sourceObj = source.sourceObj;
this.isDisabled = source.isDisabled;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import {Component, ViewChild} from '@angular/core';
import {ComponentFixture, fakeAsync} from '@angular/core/testing';
import {MultiSelectComponent, IDropdownSettings} from './../src';
import {createTestingModule} from './helper';
import {ListItem} from 'ng-multiselect-dropdown/multiselect.model';


@Component({
template: ``
})
class Ng2MultiSelectDropdownMultipleSelect {
@ViewChild(MultiSelectComponent, {static: false}) select: MultiSelectComponent;
cities = [
{item_id: 0, item_text: 'Navsari'},
{item_id: 1, item_text: 'Mumbai', population: 20_961_000},
{item_id: 2, item_text: 'Bangalore', timezone: 'India Standard Time', population: 13_193_000},
{item_id: 3, item_text: 'Pune', },
{item_id: 5, item_text: 'New Delhi'}
];
selectedItem = [{item_id: 0, item_text: 'Navsari'}];
disabled: false;
dropdownSettings: IDropdownSettings = {
singleSelection: false,
idField: 'item_id',
textField: 'item_text',
selectAllText: 'Select All',
unSelectAllText: 'UnSelect All',
allowSearchFilter: true,
closeDropDownOnSelection: true,
};
}

/**
* @see https:/NileshPatel17/ng-multiselect-dropdown/issues/172
*/
describe('ng-multiselect-component: Issue#172 - custom properties support', function () {
describe('multi-select', function () {
let fixture: ComponentFixture<Ng2MultiSelectDropdownMultipleSelect>;
beforeEach(
fakeAsync(() => {
fixture = createTestingModule(
Ng2MultiSelectDropdownMultipleSelect,
`<div class='container'>
<ng-multiselect-dropdown name="city" [data]="cities"
[(ngModel)]="selectedItem" [settings]="dropdownSettings"
(onSelect)="onItemSelect($event)"
[disabled]="disabled">
</ng-multiselect-dropdown>
</div>`);
})
);

it('getSourceObj() should return an new object instance with the omitted "item_id", "item_text", and "disabled" properties', () => {
const mockObject = {item_id: 2, item_text: 'Bangalore', timezone: 'India Standard Time', population: 13_193_000};
const expected = {timezone: 'India Standard Time', population: 13_193_000};

const result = fixture.componentInstance.select.getSourceObj(mockObject);

expect(result).toEqual(expected);
expect(Object.keys(mockObject).length).toEqual(4); // check original object is not mutated
});

it('objectify() should return an new object instance with the custom properties included', () => {
const mockObject = {id: 2, text: 'Bangalore', sourceObj: {timezone: 'India Standard Time', population: 13_193_000}};
const expected = {item_id: 2, item_text: 'Bangalore', timezone: 'India Standard Time', population: 13_193_000};

const result = fixture.componentInstance.select.objectify(mockObject as ListItem);

expect(result).toEqual(expected);
});
});
});