2017-09-23 168 views
0

當我得到所有的仇恨後,我知道有一個關於這個問題的線程,但我還沒有設法找到我的問題的解決方案。我是一名新秀。 我想做的只是當用戶在一個特定的路由時更改導航頭部背景,所以我創建了一個指令,在該指令中我檢索當前的URL,然後使用setElementStyle設置了導航頭部的樣式。爲此,我會比較當前網址是否與我存儲在變量中的特定網址匹配。 該應用程序工作正常,但我仍然得到該錯誤。ExpressionChangedAfterItHasBeenCheckedError指令中的角度

這是我的指令:

import {Directive, ElementRef, Renderer, OnInit, ChangeDetectorRef} from '@angular/core'; 
import { Router, NavigationStart, NavigationEnd, NavigationError, NavigationCancel, RoutesRecognized } from '@angular/router'; 
import 'rxjs/add/operator/filter'; 

@Directive({ 
    selector: '[styled]', 
}) 
export class StyledDirective implements OnInit { 

    constructor(public el: ElementRef, public renderer: Renderer, public _router: Router) { 
    renderer.setElementStyle(el.nativeElement, 'color', '#212121'); 
    renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'rgb(247, 247, 247)'); 
    } 

    ngOnInit(){ 
    const profileUrl = "/app/userprofile"; 
    this._router.events 
    .filter(event => event instanceof NavigationStart) 
    .subscribe((event:NavigationStart) => { 
     if (event.url == profileUrl) { 
     return this.el.nativeElement.style.backgroundColor = '#ffffff'; 
     } 
     else { 
     return this.el.nativeElement.style.backgroundColor = 'rgb(247, 247, 247)'; 
     } 
    }); 
    this._router.events 
    .filter(event => event instanceof NavigationStart) 
    .subscribe((event:NavigationStart) => { 
     if (event.url == profileUrl) { 
     return this.el.nativeElement.style.color = "#03A9F4"; 
     } 
     else { 
     return this.el.nativeElement.style.color = '#212121'; 
     } 
    }); 
    } 
} 

也許它不是最好的代碼,但過這就是我試圖解決我的問題,而且很可能有這個一個更好的解決方案。謝謝你們的幫助!

+0

我測試了你的指令,它沒有錯誤。我會盡管在this.el.native前面刪除返回....並將兩個樣式(bg顏色和顏色)在相同的if()else()中進行分組。此外,我認爲這是一種沉重的,只要改變一些css配置文件組件的顏色會更容易? – Vega

+0

感謝您的回答@Vega就像我說的,也許我的問題比創建一個指令更優雅的解決方案,但我只是在學習。所以,也許你可以引導我如何改變配置文件組件的顏色與CSS,請。 –

+0

如果你好奇爲什麼會出現這個錯誤,請閱讀[你需要知道的關於'ExpressionChangedAfterItHasBeenCheckedError'錯誤的所有信息](https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror - 錯誤 - e3fd9ce7dbb4) –

回答

0

我更喜歡這種方式

首先注入Router在構造函數,然後根據路線

constructor(private router: Router) {} 
getRoute(){ 
     if (this.router.url === '/client'){ 
     return "client"; 
     } 
    } 

在你的HTML返回功能

<header [ngClass]="getRoute()">

,並在CSS

header.client{background-color:yellow}