簡體   English   中英

Angular指令中的ExpressionChangedAfterItHasBeenCheckedError

[英]ExpressionChangedAfterItHasBeenCheckedError in Directive with Angular

討厭之后,我知道有一個關於這個問題的話題,但是我還沒有找到解決我問題的方法。 我是新秀。 我想做的是僅在用戶處於特定路線時才更改導航頭的背景,因此我創建了一條指令,在其中檢索當前網址,然后使用setElementStyle設置導航頭的樣式。 為此,我正在比較當前網址是否與我存儲在變量中的特定網址匹配。 該應用程序運行正常,但仍然出現該錯誤。

這是我的指令:

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';
      }
    });
    }
}

可能它不是有史以來最好的代碼,但這就是我試圖解決問題的方式,並且也許有一個更優雅的解決方案。 感謝您的幫助!

我喜歡這樣

首先將Router注入構造函數中,然后根據路由返回一個函數

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

在你的HTML

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

和在CSS

header.client{background-color:yellow}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM