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
.titlerule in one component also matches.titlein 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.cssfile.
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
Import it into the component, and bind each class with [class]:
src/app/card/card.ts
stylesmaps each class to its unique name, such ascardto something likecard-a1b2c3. The build writes the CSS under the unique names.- Use brackets,
styles['card'], notstyles.card. The type is an index signature, and Angular's strict TypeScript settings only allow bracket access on those. - The component exposes
stylesas 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
If TypeScript reports Cannot find module './card.module.css', add that file.
