Apply css style to all components in Angular 2 application

I have very simple and reusable CSS rules, such as:

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

I would like to reuse them for all my components. If I put this in my root directory of the AppComponent , which was downloaded using Angular, then it is not recognized by any other components in my application except the AppComponent .

I need to skip something very obvious here.

+5
source share
6 answers

Perhaps you should declare global CSS rules in your html table or external table.

+5
source

Angular adds unique classes to your component and rewrites the CSS selector added to components only to match this unique component class before adding CSS to <head> . This should emulate the DOM shadow style encapsulation.

You can get around this with

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

  • Add CSS to index.html directly. Angular does not rewrite CSS that is not added to components.

  • use a "CSS combinator shadow piercing" * >>> someSelector { ... } , which also causes CSS to ignore unique classes added to components.
    Tip : /deep/ is an alias >>> , but works better with SASS.

+8
source

You can achieve this by changing your style to

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

and in child components you can set the encapsulation: ViewEncapsulation.None (but by default it is ViewEncapsulation.None, so you do not need to set it either).

You should now be able to use your style class for all child components.

Demo: http://plnkr.co/edit/ALgOw3FHmW8RsClI8Nnb?p=preview

+1
source

From the command line:

npm install style downloader -save-dev file downloader

Now in webpack.config.js add the following line to the loaders array:

{test: / \. (eot | woff2 | woff | ttf | svg) /, loader: 'file-loader'}

Now in your app.component.ts, after the import statements, add the following line:

required ('style! bootstrap / distance / css / bootstrap.css')

It is assumed that you are using the latest version of angular2 / angular2-seed, located here: https://github.com/angular/angular2-seed on November 8, 2016

0
source

In my opinion, you should agree with a specific strategy in this regard throughout your team.

eg. you can set encapsulation: ViewEncapsulation.None just like @sreeramu mentioned in his answer. But only for the application (root) component.

You should use CSS encapsulation as much as possible to disable it for multiple components. But applying it to only one component may work fine.

0
source

You can write your CSS inside src / styles.css

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

 "apps": [ "styles": ["styles.scss"] ] 
0
source

Source: https://habr.com/ru/post/1247153/


All Articles