7

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

enter image description here

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?

vivek v
  • 167
  • 1
  • 3
  • 16

2 Answers2

14

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:

pzaenger
  • 11,381
  • 3
  • 45
  • 46
  • How can I add `.js` file for certain `components`? – Salim Ibrohimi Sep 22 '17 at 12:09
  • Take a look e.g. [here](https://stackoverflow.com/questions/42478930/how-to-import-javascript-file-into-angular2) or [here](https://stackoverflow.com/questions/44817349/how-to-include-external-js-file-in-angular-4-and-call-function-from-angular-to-j). – pzaenger Sep 22 '17 at 12:17
  • 1
    I know that I need import my `.js` files in `.angular-cli.json > scripts: [ ... ]`, but I want use my `.js` scripts only in one component... – Salim Ibrohimi Sep 22 '17 at 12:21
  • Maybe you can ask a new question here on SO. There you can add your accordant code and so on. This might be better than using comments. – pzaenger Sep 22 '17 at 12:26
  • Yes You are right. but I think You know the answer... ) – Salim Ibrohimi Sep 22 '17 at 12:27
  • If you want to use a library from the directory _node_modules_, which you have installed via npm (maybe with the accordant _@types_-package), you should be able to do something like `import {Router} from 'express';` in your component. You do not need to use the `scripts`-array then. – pzaenger Sep 22 '17 at 12:30
  • Thanks, just now I trying to post new question about that... ) see You there...) – Salim Ibrohimi Sep 22 '17 at 12:31
6

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.

Yatharth Varshney
  • 1,973
  • 20
  • 22