skip to Main Content

I am not sure whether I am doing wrong, but I would like to see from where the issue is coming.

I have a project in Angular v18, and here is the problem statement:

I am loading some dynamic htmls from javascript and the data is coming from external JSON file.
Everything is working fine, data is loading good, component styles are loading properly all good. There is no issue here.

I have added multiple .scss individual files into abc.component.scss file through @import method.
All styles are applying properly expect to the dynamic html part.

I tried loading the dynamic html’s required .scss file globally in the style.scss file and the styles are applying properly, not sure what is the issue when I load from abc.component.scss file.

Example abc.component.scss file code:

@import '../../assets/scss/helpers/variables';
@import '../../assets/scss/helpers/mixins';
@import '../../assets/scss/components/sidebar';
@import '../../assets/scss/components/title';

Within the same file:

@import '../../assets/scss/components/table';
@import '../../assets/scss/components/cards';
@import '../../assets/scss/components/users';

The @import files are applying properly except the last tree files which is for dynamic data part

Could anyone please help me on this?

I have an alternative solution, loading the last three .scss files in global.scss file but the problem is I dont want to load this css in all the pages.

2

Answers


  1. Emulated view encapsulation only works for HTML elements which are part of the component’s template. It does not work "dynamic HTML", such as dynamically rendered elements or elements inside used components. Importing the component’s style sheets in the global styles or via angular.json fixes the issue as there is no view encapsulation anymore, however it’s not a good solution, as the styles will be in the bundle twice. A few options which could work for you:

    • Use ViewEncapsulation.None to disable the emulated view encapsulation. Note that styles may leak to other parts of your application.
    • Wrap styles for "dynamic HTML" in ::ng-deep.
    Login or Signup to reply.
  2. Since its dynamic, I believe the relative imports are now invalid, so you need to add them as absolute imports /<<path>>/something.scss then it should work.

    Provided you have added the assets directory to the assets array of angular.json.

    @import '/assets/scss/components/table';
    @import '/assets/scss/components/cards';
    @import '/assets/scss/components/users';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search