【问题标题】:RouterActiveLink doesn't work with routerLink in ng-templateRouterActiveLink 不适用于 ng-template 中的 routerLink
【发布时间】:2018-11-01 06:38:34
【问题描述】:

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

  • 应用组件
  • 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中的条件只是举例

【问题讨论】:

    标签: javascript angular angular-routing ng-template


    【解决方案1】:

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

    喜欢

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多