Sub topic 12
Using Sass in Component Styles
This chapter assumes you can write a standalone component with styleUrl, and that you know how Emulated encapsulation and :host work from the earlier chapters. It covers how Sass fits into the Angular build, what Sass can and cannot do in an encapsulated component, and the mistakes that cost the most time.
What Sass adds, and what it does not change
Sass is a CSS preprocessor. It adds variables, nesting, mixins, functions and modules, then compiles to plain CSS. Angular does not treat Sass as a separate styling system. The Sass compiler runs first, at build time, and produces ordinary CSS. Angular then treats that CSS like any other component style.
That has one important consequence. Encapsulation is a runtime concern, and Sass is a build-time concern. Sass knows nothing about _ngcontent attributes, shadow roots or :host semantics. It only sees text and emits text.
Pointing a component at a Sass file
The Angular CLI picks the preprocessor from the file extension. If you reference panel.component.scss, the build compiles it with Sass. No extra configuration is needed for styleUrl or styleUrls.
import { Component, input } from '@angular/core';
@Component({
selector: 'app-panel',
template: `
<h2 class="title" tabindex="0">{{ heading() }}</h2>
<ng-content />
`,
styleUrl: './panel.component.scss',
host: {
'[class.compact]': 'compact()',
},
})
export class PanelComponent {
heading = input.required<string>();
compact = input(false);
}The .sass extension (the indented syntax without braces) also works. Most teams use .scss, which is a superset of CSS, so existing CSS pastes in unchanged.
Inline styles are CSS unless you say otherwise
The styles metadata property takes a string. By default Angular treats that string as plain CSS, even if you write Sass syntax in it. Nesting and $variables in an inline styles block will fail or be ignored.
To compile inline styles as Sass, set inlineStyleLanguage in the build options in angular.json. Projects generated with ng new --style=scss normally already have this set. Check it if inline Sass behaves like CSS.
{
"projects": {
"app": {
"architect": {
"build": {
"options": {
"inlineStyleLanguage": "scss",
"stylePreprocessorOptions": {
"includePaths": ["src/styles"]
},
"styles": ["src/styles.scss"]
}
}
}
}
}
}This is the relevant fragment of the build options, not a whole file. The setting is project-wide. You cannot mix inline CSS and inline Sass in one project. Valid values include css, scss, sass and less.
Sharing tokens, mixins and functions
Each component stylesheet is compiled on its own. Component A cannot see a Sass variable declared in component B's file. To share code, put it in a partial (a file whose name starts with an underscore) and load it with @use.
// src/styles/_tokens.scss
$surface: #f8fafc;
$radius: 4px;
@function space($n) {
@return $n * 4px;
}
@mixin focus-ring {
outline: 2px solid var(--focus-color, #2563eb);
outline-offset: 2px;
}The component stylesheet loads the partial as a module and reads members through its namespace.
// src/app/panel/panel.component.scss
@use 'tokens' as t;
:host {
display: block;
padding: t.space(4);
border-radius: t.$radius;
background: var(--panel-background, #{t.$surface});
}
:host(.compact) {
padding: t.space(2);
}
.title {
margin: 0 0 t.space(2);
font-weight: 700;
&:focus-visible {
@include t.focus-ring;
}
}The bare name 'tokens' resolves because includePaths contains src/styles. Without that option you would write a relative path such as @use '../../styles/tokens' as t;. Relative paths survive moving the include configuration around, and the include path avoids long ../ chains. Pick one convention and keep to it.
Use `@use`, not `@import`
@use loads a file once, gives its members a namespace, and keeps private members (names starting with - or _) private. @import is deprecated in Sass and is scheduled for removal. It also dumps everything into the global scope and re-evaluates the file each time. @use rules must come before any other rules in the file except @forward and variable declarations.
Nesting interacts with encapsulation
Nesting is the Sass feature people reach for first, and it needs care in Angular. Under Emulated encapsulation, Angular adds a generated attribute selector to each compound selector in your compiled CSS. A rule such as .card .list .item therefore becomes three attribute-qualified compounds, and its specificity rises with every level.
Deep Sass nesting makes this worse. Nesting four levels deep in the source gives you a four-part selector, and each part carries an attribute. The result is a rule that is hard to override from a variant class or a test.
A practical limit: nest at most two or three levels, and prefer a flat class per element. Component templates are small, so a single class like .title is usually enough.
Nesting with `:host`
Nesting under :host works, because Sass simply prefixes the parent selector.
:host {
display: block;
.title {
font-weight: 700;
}
}This compiles to :host .title. Angular scopes it as usual. Using & to build :host.compact also compiles, but the function form is the one the earlier chapters used and the one Angular documents. Write :host(.compact) { ... } explicitly as a top-level rule. It is clearer, and nobody has to expand the & in their head to see what it targets.
Sass variables versus CSS custom properties
Sass variables and CSS custom properties look similar and solve different problems. Mixing them up is the most common design error here.
| Property | Sass variable (`$x`) | CSS custom property (`--x`) |
|---|---|---|
| Resolved | At build time | At runtime, in the browser |
| Can change per element or theme | No | Yes, through inheritance and overrides |
| Crosses component boundaries | No, each file compiles separately | Yes, it inherits through the DOM, including shadow roots |
| Usable in `@media` conditions and Sass math | Yes | No |
| Visible in dev tools | No, compiled away | Yes |
Use Sass variables for things fixed at build time: breakpoints, spacing scales, and values fed to Sass functions. Use custom properties for anything a parent, a theme or a user preference might change. The usual pattern is to keep the token values in Sass and expose them as custom properties on :root or on the component host.
Interpolation is required in custom property values
Sass does not evaluate expressions inside a custom property's value. It passes the text through as written. This is the gotcha that produces CSS containing a literal t.$surface.
@use 'tokens' as t;
:host {
// Wrong: the browser receives the text "t.$surface"
// --panel-background: t.$surface;
// Right: interpolate to insert the Sass value
--panel-background: #{t.$surface};
}The same applies in the fallback of var(), which is why the panel stylesheet above wrote var(--panel-background, #{t.$surface}).
Comparing the options for scoped Sass
Sass works with every encapsulation mode. The behavior of the compiled CSS depends only on the mode.
- Emulated (default): Sass output is scoped with generated attributes. Everything in this chapter applies directly.
- ShadowDom: the compiled CSS is placed inside the shadow root. Global Sass does not reach in, so shared mixins must be
@used in each component file to be applied there. - None: the compiled CSS is added to the page as global CSS. Sass nesting then produces global selectors, so a nested
.titlerule can restyle every.titleon the page.
Common failures
- Sass syntax in inline
stylesfails. Cause:inlineStyleLanguageiscss. Fix: set it toscssand restart the dev server, since build options are read at startup. Can't find stylesheet to import. Cause: the path in@usedoes not resolve. Fix: checkincludePathsor use a path relative to the current file. Remember that partials are referenced without the underscore and extension.- Variable not defined. Cause: expecting a variable from another component's file or from
styles.scss. Fix: move it into a partial and@useit. - Duplicate CSS in the bundle. Cause: a partial with real rules loaded from many components. Fix: split it into a token partial and a global stylesheet.
- Literal
$text in a custom property. Cause: no#{}interpolation. - Overrides that will not win. Cause: deep nesting plus per-compound attributes. Fix: flatten the selectors.
Putting it together
A reasonable arrangement for a medium-sized app has three layers:
src/styles/_tokens.scssholds variables, functions and mixins, with no output of its own.src/styles.scssis the global stylesheet. It loads the tokens, emits the reset and typography rules once, and defines the custom properties on:root.- Each component has a short
.scssfile that@uses the tokens, styles:hostand a handful of flat classes, and reads theme values throughvar().
This keeps Sass doing what it is good at (build-time authoring) and leaves runtime theming to custom properties, which cross component boundaries without any encapsulation workaround.
Exercise
A component declares styles: followed by a template string that contains $gap: 8px; .row { margin: $gap; }. The build fails or the margin is missing. What are two ways to fix it?
Show answer
Inline styles are compiled as plain CSS unless inlineStyleLanguage is set to scss in the build options in angular.json, so the Sass variable is not processed. Either set inlineStyleLanguage to scss (and restart the dev server), or move the styles into a .scss file referenced by styleUrl, which the CLI compiles by its extension.
Exercise
You write --panel-background: t.$surface; inside :host in a component's SCSS file, and the panel has no background. Why, and how do you fix it?
Show answer
Sass does not evaluate expressions in custom property values, so the browser receives the literal text t.$surface, which is not a valid color. Interpolate the value: --panel-background: #{t.$surface};.
Exercise
Why should a shared Sass partial contain only variables, functions and mixins, and not real CSS rules?
Show answer
Each component stylesheet compiles separately. Every component that runs @use on the partial emits its own copy of any rules the partial contains, so the rules are duplicated across the bundle. Real rules belong in the global styles.scss, which is compiled once.