简体   繁体   中英

How to add a CSS class to Angular parent when using router-outlet for child

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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