I'm playing around with Angular 2. Currently I wonder what is the best way to implement a dynamic menu component. The idea is to have a global menu component that receives menu items for every other content component in the app.
One idea was, to have a menu.component, a menu.service and other components, that use the service. The service is referenced globally in app.module. The menu.components subscribes to an observable and dynamically add items that get pasted in. I think this is not the best solution.
Another idea is, that I put the menu selector/tag in every components template and paste data to the menu component directly. Currently I stuck in how to get items to the menu.component, so that the ngFor generates the menu items after it was initialized.
So the question is: Are there any "best practices" or common way to do this?
Guess I need some more basics in Angular 2, but it would be nice if you can lead me on the right path. It's just a learning project :)
Here is some code of what I've tried:
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HTTP_PROVIDERS } from '@angular/http';
import { AppComponent } from './app.component';
import { appRouterProviders } from './app.routes';
import { MenuComponent } from './menu.component';
import { HomeComponent } from './home.component';
@NgModule({
imports: [BrowserModule],
declarations:
[
AppComponent
],
bootstrap: [AppComponent],
providers:
[
MenuComponent,
appRouterProviders,
HTTP_PROVIDERS
]
})
export class AppModule { }
menu.component.ts
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
export class MenuItem {
name: string;
path: string;
}
@Component({
selector: 'component-menu',
template: `
<ul>
<li *ngFor="let item of menuItems"><a [routerLink]="[item.path]">{{item.name}}</a></li>
</ul>
`
})
export class MenuComponent {
public menuItems: Array<MenuItem>;
constructor() {
}
}
home.component.ts
import { Component, OnInit } from '@angular/core';
import { MenuComponent, MenuItem } from './menu.component';
@Component({
selector: 'app-home',
directives: [],
template: `<h2>Home Component</h2>
<component-menu></component-menu>`
})
export class HomeComponent implements OnInit{
private menuItems:Array<MenuItem>;
constructor(private menuComponent:MenuComponent) {
console.log('Home component ctor');
this.menuItems = [
{name:'Home', path: '/home'},
{name:'Content', path: '/content'}
];
this.menuComponent.menuItems = this.menuItems;
}
ngOnInit(){
}
}