breadcumb with json
import { Injectable } from '@angular/core';
import { Breadcrumb } from '../_modeldata/breadcrumb.model';
import * as menu from '../../assets/menu.json';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class BreadcrumbNService {
menuItems:MenuItem[];
breadcrumbss: Breadcrumb;
constructor(private http: HttpClient) {
this.menuItems = [
{
"id": "1",
name: "Home",
url: "Home",
children: [
{ id: "2", url: "Home11", name: "Submenu 1" },
{ id: "3", url: "Home12", name: "Submenu 2",
children: [
{ id: "31", url: "Home131", name: "Submenu 31" },
{ id: "32", url: "Home312", name: "Submenu 32" }
]
}
]
},
{
"id": "4",
name: "About",
url: "Home2",
children: [
{ id: "5", url: "Home21", name: "Submenu 3" }
]
},
{
id: "6",
name: "Contact",
url: "Home3",
}
];
}
findParents(childId: string): Breadcrumb[] {
let parents: Breadcrumb[] = [];
function findParentsRecursive(items: MenuItem[], childId: string): boolean {
for (let item of items) {
if (item.id === childId) {
var breadcrumb: Breadcrumb = {
url: item.url,
label: item.name
}
parents.push(breadcrumb);
return true; // Found the child, stop recursion
}
if (item.children) {
if (findParentsRecursive(item.children, childId)) {
var breadcrumb: Breadcrumb = {
url: item.url,
label: item.name
}
parents.push(breadcrumb); // Add parent if child is found in its subtree
return true; // Stop further searching in this branch
}
}
}
return false; // Child not found in this branch
}
// Start searching from the root level of the menu items
findParentsRecursive(this.menuItems, childId);
return parents.reverse();
}
}
interface MenuItem {
id: string;
name: string;
url: string;
children?: MenuItem[];
}
--------------
<ul>
<li *ngFor="let breadcrumb of (breadcrumbs)">
<a [href]="breadcrumb.url">{{ breadcrumb.label }}</a>
</li>
</ul>
Comments
Post a Comment