2017-03-31 50 views
0

以下代碼工作正常(屬性數據切換狀態)被正確設置爲活動不活動@angular:如何構建一個指令來添加基於選定路線的屬性?

<a [routerLink]="['/home']" [attr.data-toggle-state]="router.isActive('/home', true) ? 'active' : 'inactive'">Home</a> 
<a [routerLink]="['/admin']" [attr.data-toggle-state]="router.isActive('/admin', true) ? 'active' : 'inactive'">Home</a> 

不過,我想創建具有相同功能的新指令。

我的打字稿指令代碼如下所示:

Directive({ 
    selector: '[xDataToggleState]' 
}) 
export class ToggleStateDirective { 

    @Input('xDataToggleState') 
    public route: string; 

    constructor(private router: Router, private activeRoute: ActivatedRoute, private el: ElementRef, private render: Renderer) { 
     this.toggle(this.route); 
    } 

    private toggle(route: string) { 
     if (this.route) { 
      this.render.setElementAttribute(this.el.nativeElement, 'data-toggle-state', this.router.isActive(this.route, false) ? 'active' : 'inactive'); 
     } 
    } 
} 

和HTML的樣子:

<a routerLink]="['/home']" xDataToggleState="/home">Home</a> 

然而,this.route永遠是不確定的?所以指令不起作用。

回答

0

在@yurzui的幫助下,我能夠得到這個工作。不過我用ngDoCheck()

見從下面的指令工作代碼:

import { Directive, ElementRef, Input, Renderer, HostListener, OnInit, OnChanges, SimpleChanges, DoCheck } from '@angular/core'; 
import { Router, ActivatedRoute } from '@angular/router'; 

@Directive({ 
    selector: '[xDataToggleState]' 
}) 
export class ToggleStateDirective implements OnInit, DoCheck { 

    @Input('xDataToggleState') 
    public route: string; 

    constructor(private router: Router, private el: ElementRef, private render: Renderer) { 
    } 

    public ngOnInit(): void { 
    } 

    public ngDoCheck(): void { 
    this.toggle(this.route); 
    } 

    private toggle(route: string) { 
    console.debug('route=' + this.route); 

    if (this.route) { 
     console.debug('this.router.isActive(this.route, false)=' + this.router.isActive(this.route, false)); 
     this.render.setElementAttribute(this.el.nativeElement, 'data-toggle-state', this.router.isActive(this.route, false) ? 'active' : 'inactive'); 
    } 
    } 
} 

當我點擊菜單項,所有項目都更新爲管理員點擊鏈接時,可以從控制檯日誌中可以看出。

route=/home 
this.router.isActive(this.route, false)=false 

route=/admin 
this.router.isActive(this.route, false)=true 

route=/data 
this.router.isActive(this.route, false)=false 
相關問題