Add styles to a component in Angular

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

Angular gives you two possibilities: externally link a stylesheet to your component, which is a great option when you have a lot of CSS code that might make your Component look messy; or embed it inline, which you might want to do when you only have a bit of CSS you want to apply. In this lesson we will take a deeper look at the advantages of both of these methods.

[00:00] Here we have a small component which is meant to resemble a so-called panel. As you can see, we have a panel heading, we have a panel title, and we have a panel body. What we would like to do now here is to give this some more styling that it looks a bit nicer.

[00:15] The first approach is usually to go the index HTML and add a style tag here. Inside that style tag, we can then add our classes, such as panel, and add some styles that make our panel look a bit cooler. Rather than writing out the whole styles, I am simply pasting in some of them here.

[00:36] As you can see, we get already some nicer-looking panel. While this perfectly works, in a more component-oriented design, we would like to have our styling that is specific to our component be directly bound to this component.

[00:50] Just as we have our HTML part here and our JavaScript part here, we would also like to have our styling part here. Let's go back to our index HTML here, and remove our styles which we have added previously.

[01:01] Go inside our component, and in Angular, we can use our styles property for this. The styles property takes an array. Inside there, we can use the backticks, which allow us to have some multi-line strings. We paste in our CSS code here.

[01:26] Let's save it again, and you can see how the styles get applied again to our component. As you can see, there is quite some CSS code inside here, which starts to make our component file look a bit messy. With a couple of lines, this works perfectly fine, but in this case, I would rather go and split it out into a separate file.

[01:46] Instead of using the styles property, we can use the styleURLs property, which also takes an array. Now, we add the path to our styles files inside here. Let's call that styles.component.css. We obviously have to create a file also.

[02:12] Let's paste in our CSS code inside there. Let's again save it. Once the browser refresh, you can see how the styles get applied again.