简体   繁体   中英

Styling Angular2 components based on the route

I'm using a component called 'SearchComponent' in 2 routes. In the first route, the component is styled a certain way - for example there are 3 input texts that are display:block so they stack against each other. In the other route, I would like the 3 input texts to be inline-blocks.

The question is, can I use routing to conditionally change a components style? I was hoping that the @Component decorator has some conditional logic capabilities but from my readings, it isn't possible. If that was the case, then I could just use a separate styleUrl path.

Can anyone help with this?

Have you considered using route params? You could use some variable in the routes as a condition for the styling. For example:

 https://fooServer/fooApp/#/main/YourComponent;type=search1

Variable type here could be string, boolean, etc.. You would set it during the route change from the previous component.

Then in ngOnInit() you would call this._route.snapshot.params['type']; to grab the value in the route param. Then in the template, add to the tag [attr.class]="type == search1? search1Class : search2Class"

Info on route params can be found here under the 'Route definition with a parameter' header. Let me know if I misunderstood your question :)

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