Kurt Hamilton
Kurt Hamilton

Reputation: 13515

Module-scoped css files

TLDR in Angular 9, is it possible to lazy load CSS styles (not component-specific)?


My module structure:

AppModule
  |--AppFormsModule
  |--AppSharedModule

AdminModule
  |--AppFormsModule
  |--AppSharedModule

AdminModule is lazy loaded via a route in my main app module:

{
  path: appPaths.admin.path,
  canLoad: [ChapterAdminGuardService],
  loadChildren: () => import('../modules/admin/admin.module').then(m => m.AdminModule)
}

I have some amount of css that is specific to several components in the admin module. It is currently bundled into the global css file along with the css used by my main module.

Is it possible to lazy-load this css from somewhere else? With the clear benefit that extra resources aren't downloaded by the client until needed.

Ideally I would be able to specify that specific style bundles should be loaded for specific modules.

I am also open to different approaches. For example - is it possible to specify that a module should use a different version of index.html?

Upvotes: 0

Views: 1588

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71891

You can use the root component of the AdminModule, let's call it AppComponent, and use the ::ng-deep (deprecated) selector in combination with :host. Even though this selector is deprecated, they will not remove it until there is a suitable replacement option:

app.component.scss:

:host ::ng-deep {
  // This will make any paragraph element which is a child of the app-component element red 
  p {
    color: #F00;
  }
}

And by adding it as a component specific stylesheet, this will be lazy loaded when the admin module is loaded.


If you want to use ViewEncapsulation.None, you can do something like this:

@Component({
  selector: 'app-admin-module',
  styleUrls: [ './admin.component.scss' ],
  encapsulation: ViewEncapsulation.None
})
export class AdminComponent {}

admin.component.scss:

app-admin-module {
  // declare all your module styles here
  p {
    color: #F00;
  }
}

Upvotes: 2

Related Questions