简体   繁体   English

Angular指令中的ExpressionChangedAfterItHasBeenCheckedError

[英]ExpressionChangedAfterItHasBeenCheckedError in Directive with Angular

After I get all the hate, I know there's a thread about this problem but I haven't managed to find a solution for my problem. 讨厌之后,我知道有一个关于这个问题的话题,但是我还没有找到解决我问题的方法。 I'm a rookie. 我是新秀。 What I wanted to do was to change the nav header background only when the user is in a particular route, so I created a directive in which I retrieve the current url and then I styled the nav header with setElementStyle. 我想做的是仅在用户处于特定路线时才更改导航头的背景,因此我创建了一条指令,在其中检索当前网址,然后使用setElementStyle设置导航头的样式。 For that I'm comparing if the current url matches a particular url that I store in a variable. 为此,我正在比较当前网址是否与我存储在变量中的特定网址匹配。 The app is working fine but I still get that error. 该应用程序运行正常,但仍然出现该错误。

This is my directive: 这是我的指令:

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

Probably its not the best code ever but that's how I tried to resolve my problem, and probably there's a more elegant solution for this. 可能它不是有史以来最好的代码,但这就是我试图解决问题的方式,并且也许有一个更优雅的解决方案。 Thanks for your help guys! 感谢您的帮助!

I prefer this way 我喜欢这样

First inject the Router in constructor, then return a function according to route 首先将Router注入构造函数中,然后根据路由返回一个函数

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

in your html 在你的HTML

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

and in css 和在CSS

header.client{background-color:yellow}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM