Customize mat select dropdown to allow nested values in angular - html

I'm customizing angular material select/autocomplete to allow nested dropdowns.
Here, I wanted to have one parent dropdown with many childs. If I expand particular parent dropdown, only childs of that dropdown should expand or collapse. Similarly, checkbox event should be selected in the same scenario.
Here, I got [object object] when I select the dropdowns.
console log is provided to give the values selected/unselected.
Can someone help on this?
STACKBLITZ
<mat-form-field appearance="fill">
<mat-label>Toppings</mat-label>
<input type="text" matInput placeholder="Select Users" aria-label="Select Users" matInput [matAutocomplete]="auto" [formControl]="states">
<mat-autocomplete #auto="matAutocomplete">
<mat-select-trigger>
{{states.value ? states.value[0] : ''}}
<span *ngIf="states.value?.length > 1" class="example-additional-selection">
(+{{states.value.length - 1}} {{states.value?.length === 2 ? 'other' : 'others'}})
</span>
</mat-select-trigger>
<mat-optgroup *ngFor="let group of stateList">
<div>
<mat-checkbox [checked]="group.selected" (change)="toggleParent($event, group)" (click)="$event.stopPropagation()">
{{group.letter}}
</mat-checkbox>
<button mat-button (click)="expandDocumentTypes(group)">
<mat-icon>keyboard_arrow_down</mat-icon>
</button>
</div>
<mat-option *ngFor="let name of group.names" [value]="name" [ngClass]="isExpandCategory[group.letter] ? 'list-show' : 'list-hide'">
<mat-checkbox [checked]="group.checked" (change)="toggleSelection($event, name, group)" (click)="$event.stopPropagation()">
{{name}}
</mat-checkbox>
</mat-option>
</mat-optgroup>
</mat-autocomplete>
</mat-form-field>
export class SelectCustomTriggerExample {
constructor(private _formBuilder: FormBuilder) {}
// stateForm: FormGroup = this._formBuilder.group({
// stateGroup: '',
// });
// toppings = new FormControl();
isExpandCategory: boolean[] = [];
toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
stateRecord: any = [];
states = new FormControl();
expandDocumentTypes(group: any) {
console.log("expanding dropdown", group);
this.isExpandCategory[group.letter] = !this.isExpandCategory[group.letter];
// expand only selected parent dropdown category with that childs
}
toggleSelection(event: any, name: any, group: any) {
debugger;
console.log("toggleSelection", name, event.checked, group);
if (event.checked) {
console.log("stastateRecordtelist", this.stateRecord);
this.stateRecord.push(name);
this.states.setValue(this.stateRecord);
console.log("toggleselection ", this.states.value);
} else {
this.stateRecord = this.stateRecord.filter((x: any) => x !== name);
console.log("else toggleselection", name, group, this.states.value);
this.states.setValue(this.states.value.filter((x: any) => x !== name));
console.log("after filter ", this.states.value);
//this.states.setValue([]);
}
}
toggleParent(event: any, group: any) {
debugger;
group.checked = event.checked;
console.log("event", event.checked, "group", group, "states value", this.states.value);
let states = this.states.value;
states = states ? states : [];
if (event.checked) {
states.push(...group.names)
} else {
console.log("else", states);
group.names.forEach((x: string) => {
if (states.indexOf(x) > -1) {
states.splice(states.indexOf(x), 1)
}
});
}
this.states.setValue(states);
console.log("statesvalue", this.states.value);
if (!event.checked) {
this.states.setValue(this.states.value.filter((x: any) => !x.includes(group.names)))
//this.states.setValue([]);
}
console.log("final statesvalue", this.states.value);
}
stateList = [{
"letter": "A",
"checked": false,
"names": [{
"id": 1,
"type": "Alabama"
},
{
"id": 2,
"type": "Alaska"
},
{
"id": 3,
"type": "Arizona"
},
{
"id": 4,
"type": "Arkansas"
}
]
},
{
"letter": "C",
"checked": false,
"names": [{
"id": 8,
"type": "California"
},
{
"id": 9,
"type": "Colorado"
},
{
"id": 10,
"type": "Connecticut"
}
]
},
{
"letter": "D",
"checked": false,
"names": [{
"id": 18,
"type": "Delaware"
},
{
"id": 19,
"type": "Denwer"
}
]
}
];
}
Expected output should look like below

Replace your toggleParent function with below given. You can also find solution in the stackblitz: https://stackblitz.com/edit/angular-f5mizr-final-pxdgby
toggleParent(event: any, group: any) {
debugger;
group.checked = event.checked;
console.log("event", event.checked, "group", group, "states value", this.states.value);
let states = this.states.value;
states = states ? states : [];
if (event.checked) {
states.push(...group.names.filter((x: any) => !states.includes(x.type)).map((x: any) => x.type))
} else {
console.log("else", states);
group.names.forEach((x: any) => {
if (states.indexOf(x.type) > -1) {
states.splice(states.indexOf(x.type), 1)
}
});
}
this.states.setValue(states);
console.log("statesvalue", this.states.value);
if (!event.checked) {
this.states.setValue(this.states.value.filter((x: any) => !x.includes(group.names)))
//this.states.setValue([]);
}
console.log("final statesvalue", this.states.value);
this.stateRecord = this.states.value;
}

Related

Angular 13 - How to get pager details from the JSON response

I work on Angular 13 and I face an issue in that I can't retrieve pager data from the JSON.
The items array returned success but I can't return pager details.
So how to do it?
{
"items": [
{
"id": 3,
"itemNameER": "قلم",
"itemNameEN": "pen",
"description": "1"
},
{
"id": 4,
"itemNameER": "قلم",
"itemNameEN": "pencil",
"description": null
},
{
"id": 5,
"itemNameER": "قلم",
"itemNameEN": "pen2",
"description": null
},
{
"id": 8,
"itemNameER": "car",
"itemNameEN": "car",
"description": "1"
},
{
"id": 9,
"itemNameER": "mobile",
"itemNameEN": "mobile",
"description": "1"
}
],
"pager": {
"numberOfPages": 2,
"currentPage": 1,
"totalRecords": 6
}
}
What I had try is:
items?:ItemsData[];
export interface ItemsData {
id:number;
itemNameER:string;
itemNameEN:string;
description:string;
}
retrieveAllItems(pageNumber: number = 0): void {
this.erpservice.getAll(pageNumber)
.subscribe(
data => {
this.items=data.items;
console.log(data);
},
error => {
console.log(error);
});
}
How to extract pager data from JSON for the numberOfPages, currentPage and totalRecords?
Updated post
This is the information for the getAll return type.
So how to get pager data details?
export interface DataWrapper {
items: ItemsData[];
}
getAll(pageNumber: number): Observable<DataWrapper> {
let params = new HttpParams();
if (pageNumber)
params = params.append('pageNumber', pageNumber);
let httpOptions = {
params: params
};
return this.http.get<DataWrapper>(baseUrl,httpOptions);
}
What I had try is:
pager: any;
this.pager = data.pager;
But I get an error:
Property 'pager' does not exist on type 'DataWrapper'.ts(2339)
<ul>
<li *ngFor="let item of items | paginate: { currentPage:pager.currentPage }; let i = index">
{{ pager.numberOfPages * (pager.currentPage - 1) + i }}
</li>
</ul>
The error message is quite clear. The DataWrapper interface doesn't have a pager property.
You need to:
Add the pager property into DataWrapper interface.
Define the IPager interface.
export interface DataWrapper {
items: ItemsData[];
pager: IPager;
}
export interface IPager {
numberOfPages: number;
currentPage: number;
totalRecords: number;
}

How to group suggestions nested list in the primeng autocomplete angular 8

I am trying to group the autocomplete suggestions and would like to render them in primeng.
How we can add a custom template in primeng?
my data
data = [{"id":"m1","name":"menu1","val":"D","items":[{"id":"d1","name":"datanested1","val":"D","items":[{"id":"1","name":"direct Data","val":"E"},{"id":"2","name":"test","val":"E"}]}]},{"id":"d2","name":"menu2","val":"D","items":[{"id":"21","name":"test21","val":"E"},{"id":"22","name":"test23","val":"E"}]},{"id":"d3","name":"menu3","val":"D","items":[{"id":"31","name":"test data 3","val":"E"},{"id":"32","name":"test data 4","val":"E"}]}]
Is there any other libraries available in angular 8 which support this?
I would like to achieve something like this when users start searching in autocomplete...
Menu1 - header
datanested1 -subheader
direct Data -values
test -values
Menu2 - header
test21-values
test23-values
Menu3 - header
test data 3-values
test data 4-values
1. if the user types "direct" in the input box...
Menu1 - header
datanested1 -subheader
direct Data -values
2. if the user types "data" in the input box...
Menu3 - header
test data 3-values
test data 4-values
3. if the user types "menu" in the input box...
Menu1 - header
datanested1 -subheader
direct Data -values
test -values
Menu2 - header
test21-values
test23-values
Menu3 - header
test data 3-values
test data 4-values
I have tried the following example in stackblitz.
https://stackblitz.com/edit/primeng-7-1-2-qtsnpm
In the below approach we will reduce the array to a simple structure
[
{
"id": "m1",
"name": "menu1",
"val": "D",
"search": ["m1", "d1", "1", "2", "menu1", "datanested1", "direct Data", "test"],
"depth": 2
},
{
"id": "d1",
"name": "datanested1",
"val": "D",
"search": ["d1", "1", "2", "datanested1", "direct Data", "test"],
"depth": 1
},
{
"id": "1",
"name": "direct Data",
"val": "E",
"search": ["1", "direct Data"
],
"depth": 0
},
...
]
The idea is this, we will use the depth to format out text while the search for searching.
maxDepth = 0;
reducedArray = (arr, depth = 0, parentSearch = []) => {
this.maxDepth = Math.max(this.maxDepth, depth);
if (!arr) {
return [];
}
return arr.reduce((prev, { items, ...otherProps }) => {
// const depth = this.findDepth({ items, ...otherProps });
const search = [
...this.getProps({ items, ...otherProps }, "id"),
...this.getProps({ items, ...otherProps }, "name")
];
const newParentSearch = [...parentSearch, otherProps.name, otherProps.id];
return [
...prev,
{ ...otherProps, search, depth, parentSearch },
...this.reducedArray(items, depth + 1, newParentSearch)
];
}, []);
};
getProps = (item, prop) => {
if (!item.items) {
return [item[prop]];
} else {
return [
item[prop],
...item.items.map(x => this.getProps(x, prop))
].flat();
}
};
We can apply styles like below
getStyle(depth) {
return {
color: depth === 0 ? "darkblue" : depth === 1 ? "green" : "black",
paddingLeft: depth * 7 + "px",
fontWeight: 800 - depth * 200
};
}
I will use reactive programming so I will convert the object to an Observable usinf of operator
data$ = of(this.reducedArray(this.data));
filteredData$ = combineLatest([this.data$, this.filterString$]).pipe(
map(([data, filterString]) =>
data.filter(
({ search, parentSearch }) =>
!![...search, ...parentSearch].find(x => x.includes(filterString))
)
)
);
We now done, the remaining is to update html
<p-autoComplete [(ngModel)]="cdsidvalue" [suggestions]="filteredData$ | async"
(completeMethod)="filterString$.next($event.query)" field="name" [size]="16" placeholder="Menu" [minLength]="1">
<ng-template let-menu pTemplate="item">
<span
[ngStyle]="getStyle(menu.depth)" >{{ menu.name }}</span>
</ng-template>
</p-autoComplete>
Demo Here
Update
Since we are using reactive programming, refactoring to accept http requests is quite easy, simply replace the observable with an http request
data$ = this.http.get<any[]>("my/api/url");
filteredData$ = combineLatest([this.data$, this.filterString$]).pipe(
map(([data, filterString]) =>
this.reducedArray(data).filter(
({ search, parentSearch }) =>
!![...search, ...parentSearch].find(x => x.includes(filterString))
)
)
);
See this update in action
I have also updated the html to add loading message, we do not want to display a form without data
Patel , Yes you can add Group Header in NgPrime
.ts
adminentrylistSearch = [
{
Grp_Header:'THIS IS Header 1' ,
cdsid: "0121",
firstname: "FirstName1",
lastname: "LastName1",
fullname: "LastName1, FirstName1"
},
{
cdsid: "0122",
firstname: "FirstName1",
lastname: "LastName2",
fullname: "LastName2, FirstName2"
},
{
cdsid: "0123",
firstname: "FirstName3",
lastname: "LastName3",
fullname: "LastName3, FirstName3"
},
{
Grp_Header:'THIS IS Header 2',
cdsid: "0124",
firstname: "FirstName4",
lastname: "LastName4",
fullname: "LastName4, FirstName4"
},
{
cdsid: "0125",
firstname: "FirstName5",
lastname: "LastName5",
fullname: "LastName5, FirstName5"
},
{
cdsid: "0126",
firstname: "FirstName6",
lastname: "LastName6",
fullname: "LastName6, FirstName6"
},
{
cdsid: "0127",
firstname: "FirstName7",
lastname: "LastName7",
fullname: "LastName7, FirstName7"
}
];
.html
<p-autoComplete [(ngModel)]="cdsidvalue" [suggestions]="filteredCountriesSingle" [dropdown]="true"
(completeMethod)="filterCountrySingle($event)" field="firstname" [size]="16" placeholder="CDSID">
<ng-template let-adminentrylistSearch [ngIf]="adminentrylistSearch.index" pTemplate="text">
<div class='unclickable-header'>
<span [style.font-weight]="adminentrylistSearch.Grp_Header ? 'bold' : null"> {{adminentrylistSearch.Grp_Header ? adminentrylistSearch.Grp_Header : adminentrylistSearch.firstname}} </span>
</div>
</ng-template>
</p-autoComplete>
Check Result here...
Demo
In your primeng version (7.1.2) grouped autocomplete is not supported. But it's supported in latest version(11.3.0). Please see below image and follow https://www.primefaces.org/primeng/showcase/#/autocomplete

Recursive rendering of JSON tree with HTML elements (Input, Radio, etc.)

I am quite new to React and working with JSON structures. I am trying to construct a recursive render of a JSON tree structure that dynamically renders individual HTML elements (e.g. radio buttons, dropdown menus, etc.) from the tree. I have seen other implementations, but they do not have nested HTML elements that differ from li, ul, etc. They also do not typically have different naming conventions further down the tree (e.g. attributes, options).
The tree looks like this:
{
"id": "1",
"name": "Animals",
"color": "#e37939",
"shape": "bounding_box",
"attributes": [
{
"id": "1.1",
"name": "Type",
"type": "radio",
"required": false,
"options": [
{
"id": "1.1.1",
"optionName": "Cats",
"optionValue": "cats",
"options": [.... and so on
};
What I ultimately what to achieve is to get to a format where one clicks the 'Animals button', which then renders the nested radio button, and if one selects the 'cats' option value it'd render the next dropdown menu. I have set up an initial set of methods, but I can't quite figure out how to dynamically render the next set of nested options when an option is clicked. I have created a React fiddle here: https://codesandbox.io/s/vigilant-grothendieck-jknym
The biggest challenge is to get the nested recursive options embedded in an options group. I haven't been able to figure out how to do that yet.
I have created a datastructure for what you want to achieve , altho i have tweaked it a bit as there are parts of it redundant but you can still keep both data structure and convert between them.it goes recursively as deep as you want it to go.
const prodList = [
{
id: "1",
name: "Animals",
options: [
{
id: "1.1",
name: "Type",
inputType: "radio",
options: [
{
id: "1.1.1",
name: "Cats",
value: "Cats",
inputType: "select",
options: [
{ id: "1.1.1.1", name: "Siamese Grey", value: "Siamese Grey" },
{ id: "1.1.1.2", name: "Siamese Black", value: "Siamese Black" },
{ id: "1.1.1.3", name: "Siamese Cute", value: "Siamese Cute" },
{ id: "1.1.1.4", name: "House Cat", value: "House Cat" },
{ id: "1.1.1.5", name: "House Cat", value: "House Cat" }
]
},
{ id: "1.1.2", name: "Dogs", value: "Dogs" },
{ id: "1.1.3", name: "Cows", value: "Cows" }
]
}
]
}
];
above is the data structure where you have "inputType" property that helps determining what component to show. we will have a basic component , a radio component and a select component of each type which can render each other inside them.
export default class ProductsPage extends Component {
render() {
let prodItems = prodList.map(p => {
return <MainContentManager data={p} key={p.id} />;
});
return <div>{prodItems}</div>;
}
}
class MainContentManager extends Component {
render() {
let renderObj = null;
renderObj = basicMethod(renderObj, this.props.data);
return (
<div>
<h6> {this.props.data.name}</h6>
{renderObj}
</div>
);
}
}
class RadioButtonManager extends Component {
constructor(props) {
super(props);
this.state = {
activeOptionIndex: 0
};
this.handleInputClick = this.handleInputClick.bind(this);
}
handleInputClick(index) {
this.setState({
activeOptionIndex: index
});
}
render() {
let renderObj = null;
let renderDat = null;
renderDat = this.props.data.options.map((op, index) => {
return (
<label key={op.id}>
<input
type="radio"
onChange={e => {
this.handleInputClick(index);
}}
checked={index == this.state.activeOptionIndex ? true : false}
/>
{op.name}
</label>
);
});
renderObj = basicMethod(renderObj, {
options: [this.props.data.options[this.state.activeOptionIndex]]
});
return (
<div>
<h6> {this.props.data.name}</h6>
{renderDat}
{renderObj}
</div>
);
}
}
class SelectManager extends Component {
constructor(props) {
super(props);
this.state = { value: "", activeOptionIndex: 0 };
this.handleInputClick = this.handleInputClick.bind(this);
}
handleInputClick(value) {
let activeOptionIndex = this.state.activeOptionIndex;
if (this.props.data.options) {
for (let i = 0; i < this.props.data.options.length; i++) {
if (this.props.data.options[i].value == value) {
activeOptionIndex = i;
}
}
}
this.setState({
value: value,
activeOptionIndex: activeOptionIndex
});
}
render() {
let renderObj = null;
let selectOptions = this.props.data.options.map((op, index) => {
return (
<option key={op.value} value={op.value}>
{op.name}
</option>
);
});
renderObj = basicMethod(renderObj, {
options: [this.props.data.options[this.state.activeOptionIndex]]
});
return (
<div>
<select
onChange={e => {
this.handleInputClick(e.target.value);
}}
>
{selectOptions}
</select>
{renderObj}
</div>
);
}
}
function basicMethod(renderObj, data) {
if (data && data.options) {
renderObj = data.options.map(op => {
!op && console.log(data);
let comp = null;
if (op.inputType == "radio") {
comp = <RadioButtonManager data={op} key={op.id} />;
} else if (op.inputType == "select") {
comp = <SelectManager data={op} key={op.id} />;
} else {
comp = <MainContentManager data={op} key={op.id} />;
}
return comp;
});
}
return renderObj;
}
ask anything if it is unclear or you want it a bit different.

filtering by pipe: Template parse Error Angular4

its my first time with "pipe" so I think I missed few things:
I have a JSON file which contain data of products. the products can be sort by "ProductTags" - JSON with the tag they can be filter by. also, I have JSON Which contain details about the filter:
"PriceFilter": [
{
"TagId": 20,
"Type": "Budget",
"Value": 5,
"Values": null,
"DisplayText": "$5",
"Order": null
},
{
"TagId": 21,
"Type": "Budget",
"Value": 10,
"Values": null,
"DisplayText": "$10",
"Order": null
}]
product:
"Products": [
{
"ProductId": 206419,
"ProductTitle": "Mom is Fabulous Fruit Box - Good",
"ProductTags": [ 20, 2, 3, 4 ]
}]
I need to order the products using the tags in this way: price
store. html
<table>
<tr *ngFor="let P of PriceFilter | filter : term | orderBy: 'Price'">
<td>{{PriceFilter.DisplayText}}</td>
</tr>
</table>
store component:
stores=[];
products=[];
PriceFilter = [];
GenderFilter =[];
filtered=[];
constructor(private _storeService:StoreService) { }
ngOnInit() {
this._storeService.getProducts()
.subscribe(data =>{
this.products = data.Stores.Products;
this.stores=data.Stores;
this.PriceFilter = data.PriceFilter;
this.GenderFilter = data.GenderFilter;
console.log(data.PriceFilter)
console.log(data.GenderFilter)
console.log(data.Stores)
});
}
filter pipe:
transform(items: any[], term): any {
console.log('term', term);
return term
? items.filter(item => item.ProductTags.indexOf(term) !== -1)
: items;
}
orderBy pipe:
export class OrderbyPipe implements PipeTransform {
transform(items: any[], orderBy: string): any {
console.log('orderdBy', orderBy);
return items.sort((a, b) => {return b[orderBy] - a[orderBy]});
}

Ionic 3 filter nested JSON with ionic searchbar

I have a question how to use ionic searchbar to filter items in a nested JSON object. As I've tried to filter the header item it worked perfectly fine but it does not work for the name wrap inside the brands.
{
"items": [{
"header": "A",
"brands": [{ "name": "Apple", "id": "1" }, { "name": "Adidas", "id": "2" }]
},
{
"header": "B",
"brands": [{ "name": "Bose", "id": "3" }, { "name": "Boss", "id": "4" }, { "name": "Birkenstock", "id": "5" }]
},
{
"header": "M",
"brands": [{ "name": "McDonalds", "id": "6" }]
}
]
}
My search.ts:
private result: any[];
private searchItems: any;
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private http: Http
) {
let localData = this.http.get('assets/search-brand.json').map(res => res.json().items);
localData.subscribe(data => {
this.result = data;
});
this.initializeItems();
}
initializeItems() {
this.searchItems = this.result;
}
getItems(ev: any) {
// Reset items back to all of the items
this.initializeItems();
// set val to the value of the searchbar
let val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.searchItems = this.searchItems.filter((item) => {
return (item.header.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}
My code (search.html):
<ion-searchbar (ionInput)="getItems($event)"></ion-searchbar>
<p>{{test}}</p>
<ion-list *ngFor="let item of searchItems; let i = index">
<ion-list-header>
{{item.header}}
</ion-list-header>
<ion-item *ngFor="let brands of item.brands; let j = index" (click)="selectedBrand(brands.id)">{{brands.name}}</ion-item>
</ion-list>
This one is working for filtering the brands.name it said .toLowerCase() is not a function.
Your JSON data maybe have some element with header == null or does not have brands propertive. So to ensure the search work properly, you should handle these case by if statement. You need to rewrite filter function to get expected output.
Try this:
this.searchItems = this.searchItems.map((item)=>{
if(item && item.brands && item.brands.length > 0){
item.brands = item.brands.filter(brand=>{
if(!brand.name) return false;
return brand.name.toLowerCase().indexOf(val.toLowerCase()) > -1;
});
}
retrun item;
})