Home > Software design >  ngClass changing class dependant on route
ngClass changing class dependant on route

Time:08-19

I'm trying to change the div class depending on the route (/home)

I thought this would do the trick:

 [ngClass]="{'background_image':router.url === '/home'}

But it seems to not have the effect i was looking for..

Will I need to pass the route into a variable and feed it through the ngClass?

I cannot find any solutions online to this issue.

CodePudding user response:

I would create a getter in to the component .ts file where the boolean value is calculated. For instance:

get isRouteHome(): boolean {
    // logic here
    this.activatedRoute.url === RouterPaths.home;
}

edit: I forgot that I usually make string enums for my route paths (here: RouterPaths)

And in template:

[ngClass]="{'background_image': isRouteHome }"

CodePudding user response:

The only is declare in constructor Router as public:

constructor(public router:Router){}

Remember in .html you only can use variables public (by defect all the variables in Angular are public). BTW you can also use

[class.background_image]="router.url === '/home'"

a stackblitz

  • Related