1

How to add a specific class to a nav bar based on its component using angular 5

Basically, I'm trying to create an Angular 5 App. Now in this app, I've multiple components like HomeComponent, AboutComponent, ContactComponent. Now I want my nav bar's background completely transparent in the Home Component but black in other components.

I'm using bootstrap 4 also in this project. So in other components, I just want to add bg-primary class to my navbar and in the home component, I just want to remove that class and some CSS styles.

how can I achieve it?

Here is the code for my nav bar

<nav class="navbar navbar-expand-lg navbar-dark text-uppercase bg-primary w-100 position-fixed">
    ........
    .......
</nav>
nyi
  • 3,123
  • 4
  • 22
  • 45
  • How are all of these components related? Do they each individually include your component the nav bar is in as part of their template? – Daniel W Strimpel May 04 '18 at 20:41
  • You should be able to use the `NgClass` directive for that. Check out this post showing it's use case : https://stackoverflow.com/questions/35269179/angular-conditional-class-with-ngclass – Garreth Golding May 04 '18 at 20:43
  • No, the nav bar component is added in the main app component and then I'm using a router to add the specific component – Abhishek Chatterjee May 04 '18 at 20:43
  • You'll want to make use of a service to communicate between these components and the nav bar to let it know which component is currently showing. The Angular docs discuss how to create services that communicate this way: https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service – Daniel W Strimpel May 04 '18 at 20:59

1 Answers1

1

There might be a simple way of doing that. If you have a routerLink in your navbar that links to your home component you can use the routerLinkActive directive to find out if the route is active at the moment.

<a [routerLink]="['/home']" routerLinkActive #homeActive="routerLinkActive">

With the second part #homeActive="routerLinkActive" you define a template variable that will be either true or false, depending on if we are on the home route.

Then in your navbar you can use that variable to control the class.

<nav class="..." [class.bg-primary]="!homeActive">

The bg-primary class will be applied when the home route is not active.

If I'm not mistaken you have to make sure that your home route is something different than /, otherwise routerLinkActive will be true for every route.

See in the docs for more details about the directive.

tom van green
  • 1,674
  • 10
  • 14