前提准备:
构建好一个Angular2应用
熟悉CSS的flex布局风格
1 利用flex进行布局
1.1 创建三个组件
app-header app-main app-footer
1.2 在主组件中编写大体结构代码
<div class="site"> <header> <app-header></app-header> <!-- 页眉组件 --> </header> <main> <app-main></app-main> <!-- 内容组件 --> </main> <footer> <app-footer></app-footer> <!-- 页脚组件 --> </footer> </div>
1.3 在全局样式中编写代码实现flex风格布局
/* You can add global styles to this file, and also import other style files */
@import '~@angular/material/prebuilt-themes/deeppurple-amber.css'; // 导入material的内建主体
html, body, app-root, md-sidenav-container, .site {
width: 100%;
height: 100%;
margin: 0;
}
.site {
display: flex;
flex-direction: column;
}
header {
background-color: skyblue;
}
main {
background-color: grey;
flex: 1;
}
footer {
background-color: skyblue;
}
1.3 布局效果如下
2 利用MdSidenavModule快速构建侧边栏
2.1 下载相关的依赖包
cnpm i --save @angular/material@2.0.0-beta.7
技巧01:使用 materil 时需要将material的主题引入到全局样式中,引入全局样式有两种方式
方式一:在 styles.scss 中通过 @import 引入,例如
@import '~@angular/material/prebuilt-themes/deeppurple-amber.css';
方式二:在 .angular-cli.json 文件中为styles添加元素
参考博文:点击前往
2.2 在主模块中引入MdSidenavModule模块
import { MdSidenavModule } from '@angular/material';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MdSidenavModule } from '@angular/material';
import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import { HeaderComponent } from './frame/header/header.component';
import { MainComponent } from './frame/main/main.component';
import { FooterComponent } from './frame/footer/footer.component';
import { SidebarComponent } from './frame/sidebar/sidebar.component';
@NgModule({
declarations: [
AppComponent,
TestComponent,
HeaderComponent,
MainComponent,
FooterComponent,
SidebarComponent
],
imports: [
BrowserModule,
MdSidenavModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }