我正在使用<mat-nav-list>
组件来显示导航栏,还使用header(i,e mat-toolbar)
来显示单击的list-items(ex Home 1)
,如下所示:
list -item(ex Home 2)
。Home 2
的意思是Home 2
应该显示在header.
Stackblitz link
答案 0 :(得分:2)
您可能只是使用*ngFor
来遍历listItems
使用selectedItem
属性并在菜单项的click
上进行设置:
export class SelectionListComponent {
selectedItem = '';
listItems = [
{ linkTitle: 'Home 1', link: '/home-a' },
{ linkTitle: 'Home 2', link: '/home-b' },
{ linkTitle: 'Home 3', link: '/home-c' },
{ linkTitle: 'Home 4', link: '/home-d' },
{ linkTitle: 'Home 5', link: '/home-e' },
];
handleClick(selectedItem) {
this.selectedItem = selectedItem.linkTitle;
}
}
现在,要使Nav Link处于活动状态,您只需定义路径,然后应用routerLinkActive
指令,并为其指定要在其活动时要应用于其的类的名称。 / p>
在模板中:
<mat-toolbar color="primary">{{ selectedItem }}</mat-toolbar>
<mat-nav-list>
<mat-list-item *ngFor="let item of listItems" (click)="handleClick(item)">
<mat-icon matListIcon>home</mat-icon>
<a
[routerLink]="item.link"
routerLinkActive="active"
matLine>
{{item.linkTitle}}
</a>
</mat-list-item>
</mat-nav-list>
在CSS中,您必须定义活动类:
.active {
color: #673AB7;
font-weight: bold!important;
}
然后在您的AppModule中:
@NgModule({
imports: [
...
RouterModule.forRoot([
{ path: 'home-a', component : SelectionListComponent },
{ path: 'home-b', component : SelectionListComponent },
{ path: 'home-c', component : SelectionListComponent },
{ path: 'home-d', component : SelectionListComponent },
{ path: '**', component: SelectionListComponent }
])
],
...
})
export class AppModule { }
答案 1 :(得分:1)
方法::获取一个成员变量以显示在标题中,
并在每个(click)="selected='Home 1'"
上将click事件用作mat-list-item
。这样,每次单击都会相应地更改此选定变量。
<mat-toolbar color="primary"> {{selected}}</mat-toolbar>
<mat-nav-list>
<mat-list-item [routerLink]="['/home1']"
(click)="selected='Home 1'"
[routerLinkActive]="['active']">
<mat-icon [class.active]="selected" matListIcon>home</mat-icon>
<a matLine>Home 1</a>
</mat-list-item>
<mat-list-item [routerLink]="['/home2']"
(click)="selected='Home 2'"
[routerLinkActive]="['active']">
<mat-icon matListIcon>home</mat-icon>
<a matLine>Home 2</a>
</mat-list-item>
<mat-nav-list>