angularlazy-loadingangular-module

Angular library with multiple entry points lazy loading


I have a custom library with some custom element like: custom-a, custom-b and custom-c. The structure is the following:

)

I'm using custom-b component in another app, by importing it on its app.module.ts. I've noticed that unless adding custom-b in the app template (adding ),custom-b.component.scss content is not used/seen on browser. Why is that? Is there lazy loading for modules by default? (No routing is used)

Thanks!


Solution

  • Okey, so I think you did miss understand the way css works in angular. and are applying a css in an improper maner.

    By telling that ViewEncapsulation.None you're removing the shadow DOM angular is generating. Which, when the components get rendered, will apply his css to every other element.

    @Component({
      selector: 'app-custom-b',
      templateUrl: './custom-b.component.html',
      styleUrls: ['./custom-b.component.css'],
      encapsulation: ViewEncapsulation.None, // <-- here
    })
    

    But this will only be applied when used.

    A component, in Angular, should be able to leave on his own and should not impact other component (Not that way at least).

    But if you wished to have a shared css file, you could do one of the following

    1: Shared CSS

    1. Create a new shared.component.css file
    2. Add you css in there
    :host {
      .test-b {
        background-color: pink;
      }
    }
    
    1. Use it in the component you wish.

    2 : Global CSS

    1. Add global css in the global_styles.css file. this will change the teat-b in your entire project

    3 : Import exported css in the angular.json file

    1. Open the angular.json file
    2. Add a new style to the styles array
    "styles": [
    "src/global_styles.css",
    "new/path/to/my/project"
    ],
    

    _here if you don't know how to export CSS _

    Explanation: ViewEncapsulation

    None

    Css will, when rendered, get applied to the entire project. prefer adding the component selector to avoid it having an impact in your project

    app-custom-b {
      // your css
    }
    

    Pro: Let you change the css of some children element that you would be able to change otherwise.

    Con: Not that good for optimization.

    Encapsulated

    Will be created in a kind of Shadow DOM.

    Pro: Optimized

    Con: You cannot change css in some children element that are in their own shadow DOM.