RouterActiveLink不能与ng-template中的routerLink一起使用

时间:2018-05-22 13:11:18

标签: javascript angular angular-routing ng-template

我已经在" 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文本:&#34;组件工作&#34;)并为点击的链接添加红色背景。< / p>

现在,如果我将元素放在标签中并在* 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 :(得分:0)

您可以直接在li tag

使用* ngIf和routerLink

private void createLvwTable(List<string> table) { int index = 0; DataTable dt = new DataTable(); foreach (string row in table) { string[] cells = row.Split('|'); if (index == 0) // header column { for (int j = 0; j < cells.Length; j++) { dt.Columns.Add(cells[j]); //dt.Rows.Add(); } } else { DataRow dr = dt.NewRow(); for (int j = 0; j < cells.Length; j++) { dr[j] = cells[j]; } dt.Rows.Add(dr); } index++; } lvwOutput.DataSource = dt; lvwOutput.DataBind(); }