简体   繁体   中英

How to add a stylesheet conditionally based on a component in Angular 2?

I have a component with a styleUrls .

This component is not shown by default because I have a *ngIf .

If true, the component is displayed in the page with the CSS. The CSS is automatically added to the document <head> .

If false, the component is not displayed anymore, but its CSS is still in the page, inside the <head> .

How can I remove this CSS from <head></head> when the component itself is not displayed?

You can use a conditional stylesheet on your index.html by using *ngIf='YOUR_COMPONENT_ROUTE_HERE === THIS_ROUTE'. Not sure if the stylesheet will load. *ngIf='YOUR_COMPONENT_ROUTE_HERE === THIS_ROUTE'. Not sure if the stylesheet will load.

You can set conditional CSS classes like this:

<element NgStyle={condition? true: false} > </element>

For example:

<element NgStyle={isNew ? 'new' : 'default' } > </element>

Let me know if you have any further questions..

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