Search code examples
cssangularencapsulation

Overriding the encapsulated :host-style of external component


Is it possible to override :host-styling of an external angular2-component?

We're making a library including a sidebar-component. This component has a default (fallback) background, but this should be overridable by css/theme used in the app.

@Component({
    selector: 'sidebar',
    styles: [`
        :host { background-color: green; }         
    `],
    template: `
        <h1>sidebar</h1>
        <ng-content></ng-content>
    `
})
export class SideBarComponent { .... }

Main App css:

<style>
    sidebar {background: red; color: yellow; }
</style>

This returns a sidebar with green background and yellow text, but I want a red background...


Solution

  • Edited:

    As found on http://blog.angular-university.io/how-to-create-an-angular-2-library-and-how-to-consume-it-jspm-vs-webpack/: add an attribute to the body-tag:

    <body override>
        <app></app>
    </body>
    

    And in your css: use a selector for this attribute:

    [override] hello-world h1 {
        color:red;
    }
    

    This way, your css does not have to be parsed.

    Previous solution:

    I've found a solution myself: instead of linking my (theming) css-file in index.html, which isn't parsed, I imported this particular css-file in the app.component.ts annotation.

    index.html:

    <!DOCTYPE html>
    <html lang="en">
        <head>
          <link rel="stylesheet/css" type="text/css" href="/assets/style/app.css" />
        </head>
        <body>
            <app></app>
        </body>
    </html>
    

    app.component.ts:

    import { ... }
    @Component({
        selector: 'app',
        styles: [`
            @import "assets/style/theme.css";
        `], 
        template: `
            ...`,
    })
    export class AppComponent {...}
    

    theme.css:

    sidebar {background: red; }