在mat-nav-list组件中显示单击的列表项值

时间:2018-11-15 10:55:54

标签: angular typescript angular-material

我正在使用<mat-nav-list>组件来显示导航栏,还使用header(i,e mat-toolbar)来显示单击的list-items(ex Home 1),如下所示:

enter image description here

  • 现在,我想在标题上显示所选的/单击的list -item(ex Home 2)
  • 点击Home 2的意思是Home 2应该显示在header.

Stackblitz link

2 个答案:

答案 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 { }

Updated StackBlitz

答案 1 :(得分:1)

演示代码: https://stackblitz.com/edit/selection-list-activelinks-example?file=app/selection-list/selection-list.component.ts

方法::获取一个成员变量以显示在标题中,
并在每个(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>