Use Scoped Component Styles in Angular

Sam Julien
InstructorSam Julien

Share this video with your friends

Send Tweet
Published a year ago
Updated 10 months ago

In other frameworks, CSS modules and CSS-in-JS are both quite popular. One of the reasons for this is the ability to add scoped styling to your app. This prevents inadvertently overwriting styles due to a shared global class somewhere. You won't hear much about these options in the Angular community, and that's because Angular comes with a scoped CSS option right out of the box. In this lesson, I'll show you how this works.

Sam Julien: [0:00] If you're wondering why you haven't heard about CSS-in-JS while you're learning Angular, it's because one of the most underrated features of Angular is that it shifts with scoped CSS by default, right out of the box.

[0:14] For example, I've got here my <h1> tag set to purple. If I change in the habit-list component, change this <h2> to an <h1> and save it, even though it switches to an <h1> tag, you can see that the color of the text is still black instead of purple.

[0:33] Likewise, if I change this from purple to blue and the page refreshes, the habit tracker text goes to blue, but the habit's text stays black. This lets us do some pretty specific styling, which is really nice. For example, if I close this and open up the habit-form component and then add a style to the array and specifically target buttons in this.

[1:01] I don't even need to create a new class. I can just say all the buttons in this component because I know that there's only one. I can just say background-color: blue and color: white and border-radius: 5px. Maybe let's also say font-size: 16px. You can see that the button changes to those styles here in this form.

[1:25] If I go over to the individual habit-item and try to add a button there, I'll just say button type = "button" and say Delete. Now, you can see that the button added, but it doesn't have any of those styles that were added to the button on the add-habit form.

[1:45] This is a really easy and powerful way to just scope your CSS styles. Let's look at what's happening in the element inspector here. If I do Inspect and just take a look at what Angular is doing here, you can see here that we've got this ngcontent around this button. That is the special scopes styling that Angular provides.

[2:09] If I do the same thing with this delete button and inspect that, you can see it doesn't have any extra styling at all. Likewise, with the headers that we made, if I inspect the Habit Tracker header, you can see this ngcontent styling there. If I do the same thing with Habits, you can see that there's no special styling.

[2:31] This is a nice feature that Angular provides without you having to do anything special. It's just there for you right out of the box.