2017-02-21 30 views
2

我有一個頁面的部分和固定的菜單。 當用戶點擊菜單項時,頁面將滾動到對應的部分。如何添加'活躍'類與角2鏈接

滾動我用https://github.com/Nolanus/ng2-page-scroll

如何添加「主動」類菜單項上點擊時也是用戶滾動到新的部分?

編輯: 進展 - 添加 '主動' 上單擊類:
我的HTML:

<ul class="nav nav-menu"> 
    <li class="" [class.active]="activeLink == 'item1'" (click)="setActiveLink('item1')"> 
     <a pageScroll href="#item1">item 1</a> 
    </li>  
</ul> 

而且在我的組件:

private activeLink: string = 'default-active-link'; 

setActiveLink(link: string){ 
    this.activeLink = link; 
} 

但如何得到它也工作滾動?

+0

發佈您的代碼? – smnbbrv

+0

也許RouterLinkActive是你在找什麼? – Amit

回答

1

根據官方文檔

的RouterLinkActive指令,您可以添加一個CSS類元素時鏈接的途徑被激活。

<a routerLink="/user/bob" routerLinkActive="active-link">Bob</a> 
When the url is either '/user' or '/user/bob', the active-link class will be added to the a tag. If the url changes, the class will be removed. 

您可以設置多個類,如下所示:

<a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a> 
<a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a> 

你可以通過精確配置RouterLinkActive:真。這隻會在url完全匹配鏈接時纔會添加類。

<a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: 
true}">Bob</a> 
+1

這沒有用,因爲我不改變頁面,一切都發生在一個頁面上。 – lovekas

1

您可以使用twostates之間過渡的角動畫:

import { 
     Component, 
     Input, 
     trigger, 
     state, 
     style, 
     transition, 
     animate 
    } from '@angular/core'; 
    import { Heroes } from './hero.service'; 
    @Component({ 
     moduleId: module.id, 
     selector: 'hero-list-basic', 
     template: ` 
     <ul> 
      <li *ngFor="let hero of heroes" 
       [@heroState]="hero.state" 
       (click)="hero.toggleState()"> 
      {{hero.name}} 
      </li> 
     </ul> 
     `, 
     styleUrls: ['./hero-list.component.css'], 
     animations: [ 
     trigger('heroState', [ 
      state('inactive', style({ 
      backgroundColor: '#eee', 
      transform: 'scale(1)' 
      })), 
      state('active', style({ 
      backgroundColor: '#cfd8dc', 
      transform: 'scale(1.1)' 
      })), 
      transition('inactive => active', animate('100ms ease-in')), 
      transition('active => inactive', animate('100ms ease-out')) 
     ]) 
     ] 
    }) 
    export class HeroListBasicComponent { 
     @Input() heroes: Heroes; 
    } 

也可參考此鏈接瞭解詳情:

https://angular.io/docs/ts/latest/guide/animations.html