CSS Modules

Give a component class names that can't clash with any other component's. With CSS Modules, the build turns each class in a .module.css file into a unique name, and you apply it from TypeScript.

When to use them

Reach for CSS Modules when:

  • Two components use the same class name. Component styles aren't isolated on Lynx: a .title rule in one component also matches .title in another. CSS Modules make each name unique. See Component styles.
  • You pick classes in TypeScript. The class names are values you can pass around, compute or store.
  • Several components share one stylesheet. Each imports the same .module.css file.

For most components, styles or styleUrl with distinctive class names is simpler.

Use a CSS Module

Write ordinary CSS in a file ending in .module.css:

src/app/card/card.module.css
.card {
  background-color: white;
  border-radius: 12px;
  padding: 16px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #333333;
}

Import it into the component, and bind each class with [class]:

src/app/card/card.ts
import { Component } from '@angular/core';
import { LYNX_ELEMENTS } from '@blotch/angular-lynx';
import styles from './card.module.css'; 

@Component({
  selector: 'app-card',
  imports: [LYNX_ELEMENTS],
  template: `
    <view [class]="styles['card']">
      <text [class]="styles['title']">Card title</text>
    </view>
  `,
})
export class Card {
  protected readonly styles = styles; 
}
  • styles maps each class to its unique name, such as card to something like card-a1b2c3. The build writes the CSS under the unique names.
  • Use brackets, styles['card'], not styles.card. The type is an index signature, and Angular's strict TypeScript settings only allow bracket access on those.
  • The component exposes styles as a field because a template can only read the component's own members.

There's nothing to configure. Any file ending in .module.css is a CSS Module.

TypeScript types

Apps created with npm create angular-lynx already have the types. They come from src/rspeedy-env.d.ts, which ng add writes:

src/rspeedy-env.d.ts
/// <reference types="@blotch/angular-lynx-build/client" />

If TypeScript reports Cannot find module './card.module.css', add that file.

Compared with component styles

Component styles (styles, styleUrl)CSS Modules
Class namesAs writtenUnique, generated by the build
ScopingNone. Emulated encapsulation doesn't rewrite selectors on Lynx, so rules apply app-wideEach name exists only in its file
How you apply themclass="title"[class]="styles['title']"
Share across filesCopy the CSS, or move it to the global stylesheetImport the same .module.css file