Importing style sheets in angular4

2020-06-17 04:32发布

问题:

Am trying upgrade my project from angular JS to angular 4. I have style sheets which i have used in angular JS project.

This is my folder structure

I created components using angular CLI. Everything works perfect but i don't know how to use my styles in angular 4 project. Can some one explain how i can use my styles globally? and also only in certain components?

回答1:

You can add your styles within the angular-cli.json:

"styles": [
  // Your styles go here
]

This is for global styles. Local styles (for a certain component) are within the accordant CSS-file, which belongs to your component, e.g. foo.component.css. By default each component has the following annotation:

@Component({
  selector: 'app-foo',
  templateUrl: './foo.component.html',
  styleUrls: ['./foo.component.css'],
})

So, foo.component.css contains the CSS for the component FooComponent.

Take a look here:

  • Component Styles
  • Global styles


回答2:

Apart from adding the css file to angular-cli.json as shown by @pzaenger you can also add it to index.html page of your app as shown below :-

<link rel="stylesheet" type="text/css" href="node_modules/bootstrap/dist/css/bootstrap.min.css" />

OR

you can even import it into an existing CSS file in your app by adding the @import statement at the top of that file as shown below :-

@import "~bootstrap/dist/css/bootstrap.min.css";

This way you can also add CDN links of the CSS file which cannot be done in angular-cli.json file. You can find a more elaborated explanation at this link.



标签: css angular