从文档
中,您可以使用示意图生成完整的导航并根据需要调整行为和方面。
ng generate @angular/material:table <component-name>
上面的命令将创建一个完全响应的导航组件,并将导入必要的模块。
如果你想手动完成,你可以看到下面的例子(基本上上面的命令会生成什么):
HTML 模板:
<mat-sidenav-container class="sidenav-container">
<mat-sidenav
#drawer
class="sidenav"
fixedInViewport
[attr.role]="(isHandset$ | async) ? 'dialog' : 'navigation'"
[mode]="(isHandset$ | async) ? 'over' : 'side'"
[opened]="(isHandset$ | async) === false"
>
<mat-toolbar>Menu</mat-toolbar>
<mat-nav-list>
<a mat-list-item href="#">Link 1</a>
<a mat-list-item href="#">Link 2</a>
<a mat-list-item href="#">Link 3</a>
</mat-nav-list>
</mat-sidenav>
<mat-sidenav-content>
<mat-toolbar color="primary">
<button
type="button"
aria-label="Toggle sidenav"
mat-icon-button
(click)="drawer.toggle()"
*ngIf="isHandset$ | async"
>
<mat-icon aria-label="Side nav toggle icon">menu</mat-icon>
</button>
<span>blog</span>
</mat-toolbar>
<!-- Add Content Here -->
<ng-content></ng-content>
</mat-sidenav-content>
</mat-sidenav-container>
打字稿文件
import { Component } from '@angular/core';
import { BreakpointObserver, Breakpoints } from '@angular/cdk/layout';
import { Observable } from 'rxjs';
import { map, shareReplay } from 'rxjs/operators';
@Component({
selector: 'it-nav-example',
templateUrl: './nav-example.component.html',
styleUrls: ['./nav-example.component.scss']
})
export class NavExampleComponent {
isHandset$: Observable<boolean> = this.breakpointObserver.observe(Breakpoints.Handset)
.pipe(
map(result => result.matches),
shareReplay()
);
constructor(private breakpointObserver: BreakpointObserver) {}
}
CSS 文件
.sidenav-container {
height: 100%;
}
.sidenav {
width: 200px;
}
.sidenav .mat-toolbar {
background: inherit;
}
.mat-toolbar.mat-primary {
position: sticky;
top: 0;
z-index: 1;
}
无论您选择如何创建导航,请确保将您的路线放置在根组件的 nav 组件中,如下所示:
app.component.html
<app-nav-example>
<router-outlet></router-outlet>
</app-nav-example>