user1381745
user1381745

Reputation: 3900

How can I apply styles globally to an Angular2 application?

To give the exact scenario I'm facing, I am trying to use Webpack to bundle Zurb's Foundation package into my application. Looking at the bundled JS, the Foundation SCSS is getting imported, but I'm not sure how to apply it to my application's render.

I tried a require('../../node_modules/foundation.scss/foundation.scss) in the root component's style attribute and that does seem to style that component's HTML, but not the HTML of any child components.

What's the correct way to do this?

Upvotes: 1

Views: 2771

Answers (3)

user1806692
user1806692

Reputation: 143

I may be misunderstanding but it sounds like you have found a way to include the main foundation css into the root component but this css is then not applied to any other components am I right?

If this is the case then I think you need to set the root component to use: encapsulation: ViewEncapsulation.None

Inside your root component you need to import this:

import {ViewEncapsulation} from '@angular/core';

and then do this:

@Component({
   moduleId: module.id,
    selector: 'global-css',
    templateUrl: 'global-css.component.html',
    styleUrls: ['global-css.component.css'],
    encapsulation: ViewEncapsulation.None
})

ViewEncapsulation.None basically says don't scope the css to this component only.

If for some reason doing this in the root component is not allowed, try creating a 'global-css' component that has ViewEncapsulation.None and then just import this component into your root app component

Upvotes: 5

Frederick Mfinanga
Frederick Mfinanga

Reputation: 1155

You can use the extract text plugin for webpack. "It moves every require("style.css") in entry chunks into a separate css output file. So your styles are no longer inlined into the javascript, but separate in a css bundle file (styles.css). If your total stylesheet volume is big, it will be faster because the stylesheet bundle is loaded in parallel to the javascript bundle."

https://github.com/webpack/extract-text-webpack-plugin

Only do this for the css you wont be modifying, as hot reload wont be available. I presume you wont be making modification to foundation.css, so only create a separate bundled css for that

Upvotes: 1

user2263572
user2263572

Reputation: 5606

If you include css files in the index.html file in your root folder they should be applied to your entire application.

Otherwise you can use the style property within your components meta data to include specific css files to specific components.

Update due to clarification in comments:

Upvotes: -1

Related Questions