2

I have a structure like this

<!-- parent -->
<div>
  <!-- child gets injected by router -->
  <router-outlet></router-outlet>
</div>

I want to add a class to the parent div if the router produces a particular child component. I saw a similar question with presumably a correct answer but it does not use the router so it will not work for me.

Stack Underflow
  • 2,363
  • 2
  • 26
  • 51
  • There is `activate` event on `router-outlet` element. Check it out https://stackoverflow.com/questions/40294262/angular-2-how-to-pass-data-to-a-child-component-without-rendering-the-child-co/40298057#40298057 – yurzui Jun 12 '18 at 17:52

1 Answers1

2

You can inject the Router into your parent component, and use [ngClass].

constructor(public router: Router) { }

Then in the template:

<div class="container" [ngClass]="{'test' : router?.url === '/home'}">

  <router-outlet></router-outlet>
</div>

This will add a class called test if the router is set to /home.

You can see it in action here

user184994
  • 17,791
  • 1
  • 46
  • 52