首页 > 解决方案 > RouterActiveLink 不适用于 ng-template 中的 routerLink

问题描述

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

只有一个模块 ( 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 中的条件只是举例

标签: javascriptangularangular-routingng-template

解决方案


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

喜欢

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


推荐阅读