首页 文章

RouterActiveLink不适用于ng-template中的routerLink

提问于
浏览
0

我在“Angular 2”中创建了一个包含三个组件的新应用程序:

  • AppComponent

  • Test1Component

  • Test2Component

只有一个模块(AppModule)引导AppComponent,声明AppComponent,Test1Component和Test2Component,并导入 RouterModule.forRoot(appRoutes) .

这是 appRoutes

const appRoutes: Routes = [

  {
    path: '',
    component: AppComponent,
    pathMatch: 'full',
},
  {
      path: 'test1',
      pathMatch: 'full',
      component: Test1Component
  },
  {
      path: 'test2',
      pathMatch: 'full',
      component: Test2Component
  }
];

这是 app.component.html

<h1>Test routerLinkActive</h1>
<ul>
  <li routerLinkActive="active">
      <a routerLink="/test1">Link 1</a>       
  </li>
  <li routerLinkActive="active">
      <a routerLink="/test2">Link 2</a>          
  </li>
</ul>
<router-outlet></router-outlet>

app.component.css 中有:

.active>a{
    background: red;
}

它工作得很好,当我点击ul中的链接时,角度加载正确的组件,显示其内容(简单的html文本:“组件工作”),并为点击的链接添加红色背景 .

现在,如果我将元素放在标签中并且我在* ngIf中引用它,则在链接点击时加载组件Test1和Test2但不添加背景 .

破碎版:

<h1>Test routerLinkActive</h1>
<ng-template #tpl1>
    <a routerLink="/test1">Link 1</a>
</ng-template>
<ng-template #tpl2>
    <a routerLink="/test2">Link 2</a>
</ng-template>
<ul>
  <li routerLinkActive="active">     
    <div *ngIf="1===1;then tpl1 else tpl1"></div>
  </li>
  <li routerLinkActive="active">      
      <div *ngIf="1===1;then tpl2 else tpl2"></div>
  </li>
</ul>
<router-outlet></router-outlet>

为什么?

PS:* ngIf中的条件仅作为示例

1 回答

  • 0

    您可以直接在li标签上使用* ngIf和routerLink

    喜欢

    <li routerLinkActive="active" *ngIf="" routerLink="/pages/page"> <a>tab name</a> </li>

相关问题