Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply css style to all components in Angular 2 app

Tags:

angular

I have very basic, and reusable css rules, such as:

.ng-invalid {
    border-left: 5px solid #a94442;
}

.ng-valid {
    border-left: 5px solid #42A948;
}

I'd like to re-use these for all of my components. If I place this in my root AppComponent, which is the one that is bootstrapped by Angular, then it's not recognized by any other components in my application other than the AppComponent.

I must be missing something very obvious here.

like image 824
mariocatch Avatar asked Apr 14 '16 20:04

mariocatch


People also ask

How do I use CSS in angular components?

Everything about CSS applies to Angular components. We can also compound component styles with components, which allows for more modular designs than regular stylesheets. We can define CSS styles in addition to template content in our components. One way to do it is to use the styles property in our component.

What is component styles in angular?

Component Styles Learn how to apply CSS styles to components. Angular applications are styled with standard CSS. That means you can apply everything you know about CSS stylesheets, selectors, rules, and media queries directly to Angular applications.

What is the best way to style angular applications?

Angular applications are styled with standard CSS. That means you can apply everything you know about CSS stylesheets, selectors, rules, and media queries directly to Angular applications. Additionally, Angular can bundle component styleswith components, enabling a more modular design than regular stylesheets.

Is the content still applicable for all angular 2 + versions?

The content is likely still applicable for all Angular 2 + versions. CSS encapsulation has always been something developers have wanted in their web applications. The ability to scope CSS to a specific component without affecting other components has been difficult to achieve.


2 Answers

You can write your CSS inside src/styles.css

or you can create your new CSS file and specify inside .angular-cli.json file

"apps": [
  "styles": ["styles.scss"]
]
like image 59
ganesh kalje Avatar answered Sep 28 '22 02:09

ganesh kalje


Angular adds unique classes to your component and rewrites the selectors of CSS added to components to only match that components unique class, before adding the CSS to the <head>. This is to emulate shadow DOM style encapsulation.

You can work around it by

  • set encapsulation: ViewEncapsulation.None which prevents rewriting styles for components where encapsulation is disabled

  • add the CSS to the index.html directly. Angular doesn't rewrite CSS that is not added to components.

  • use "shadow piercing CSS combinator" ::ng-deep someSelector { ... } which also makes the CSS ignore the unique classes added to the components.

like image 27
Günter Zöchbauer Avatar answered Sep 28 '22 03:09

Günter Zöchbauer