简体   繁体   English

如何基于Angular 2中的组件有条件地添加样式表?

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

I have a component with a styleUrls . 我有一个带styleUrls的组件。

This component is not shown by default because I have a *ngIf . 默认情况下不显示此组件,因为我有一个*ngIf

If true, the component is displayed in the page with the CSS. 如果为true,则该组件与CSS一起显示在页面中。 The CSS is automatically added to the document <head> . CSS将自动添加到文档<head>

If false, the component is not displayed anymore, but its CSS is still in the page, inside the <head> . 如果为false,则不再显示该组件,但其CSS仍在页面中的<head>

How can I remove this CSS from <head></head> when the component itself is not displayed? 当未显示组件本身时,如何从<head></head>删除此CSS?

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.可以在index.html上使用条件样式表*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: 您可以这样设置条件CSS类:

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

For example: 例如:

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

Let me know if you have any further questions.. 如果您还有其他问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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