{{ currentContent }}
Welcome to the home page!
About us...
Contact us...
以下是一个示例,展示了如何使用Angular 6+创建一个具有侧边菜单并能够更改主要内容的解决方案:
ng new sidebar-menu-example
cd sidebar-menu-example
ng generate component sidebar
sidebar.component.html文件中添加侧边菜单的HTML代码。
sidebar.component.ts文件中添加一个changeContent方法,用来更改主要内容。import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent {
@Output() contentChange = new EventEmitter();
changeContent(content: string) {
this.contentChange.emit(content);
}
}
app.component.html文件中使用侧边菜单组件,并将主要内容放在一个中。
{{ currentContent }}
Welcome to the home page!
About us...
Contact us...
- 在
app.component.ts文件中添加一个changeContent方法,用于接收侧边菜单组件发出的事件,并更新当前内容。
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
currentContent: string = 'Home';
changeContent(content: string) {
this.currentContent = content;
}
}
- 在
app.component.css文件中添加样式。
.container {
display: flex;
}
.sidebar-menu {
list-style-type: none;
padding: 0;
margin: 0;
width: 200px;
background-color: #f1f1f1;
}
.sidebar-menu li {
padding: 10px;
cursor: pointer;
}
.sidebar-menu li:hover {
background-color: #ddd;
}
.main-content {
flex-grow: 1;
padding: 10px;
background-color: #f9f9f9;
}
- 运行应用程序。
ng serve
通过上述步骤,您将能够创建一个具有侧边菜单的Angular 6+应用程序,并能够更改主要内容。
下一篇:Angular 6+ 缓存问题
相关内容