【发布时间】:2016-12-25 03:02:51
【问题描述】:
我在玩 Angular 2。 目前我想知道实现动态菜单组件的最佳方式是什么。 这个想法是有一个全局菜单组件,它接收应用程序中每个其他内容组件的菜单项。
一个想法是,有一个 menu.component、一个 menu.service 和其他使用该服务的组件。该服务在 app.module 中被全局引用。 menu.components 订阅一个 observable 并动态添加粘贴的项目。我认为这不是最好的解决方案。
另一个想法是,我将菜单选择器/标签放在每个组件模板中,并将数据直接粘贴到菜单组件。目前我一直在研究如何将项目获取到 menu.component,以便 ngFor 在初始化后生成菜单项。
所以问题是:是否有任何“最佳实践”或通用方法可以做到这一点?
我想我需要更多关于 Angular 2 的基础知识,但如果你能带领我走上正确的道路,那就太好了。这只是一个学习项目:)
这是我尝试过的一些代码:
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(){
}
}
【问题讨论】:
-
“动态菜单”非常通用。您没有对菜单提出任何要求。这个问题也是关于在 SO 上不鼓励的意见。
-
OK - 这个想法是有一个单独的菜单组件,每个“内容”组件都有自己的菜单项,这些菜单项被转移到这个菜单组件。听起来真的很简单。我认为这是一个常见的用例。
-
请编辑您的问题并发布代码,展示您尝试完成的工作以及失败的地方。
-
更多的是关于什么是实现这样一个全局菜单组件的最佳方式的问题,而不是获取特定代码的帮助。
-
但是具体的代码可以让你更容易掌握你真正想要完成的事情。请查看帮助菜单,了解要问什么问题(不问)以及如何提出好的问题。 SO 是关于具体的编程问题。好的问题通常包含代码,这些代码展示了尝试过的内容、失败的地方以及适用的具体错误消息。对于讨论,其他渠道更合适。
标签: angular