Inject Style Declarations Using Hostbinding in Angular

18,010

You need to pass the same value you would add to an element like <div style="..."> and sanitize the styles

  @HostBinding('style')
  get myStyle(): SafeStyle {
    return this.sanitizer.bypassSecurityTrustStyle('background: red; display: block;');
  }

  constructor(private sanitizer:DomSanitizer) {}

working demo

Share:
18,010

Related videos on Youtube

Andrei Voicu
Author by

Andrei Voicu

Updated on June 04, 2022

Comments

  • Andrei Voicu
    Andrei Voicu almost 2 years

    Do you guys know how I can batch inject style declarations in a component using the @HostBinding decorator? What I am trying is:

    @HostBinding('style')
    get style(): CSSStyleDeclaration {
      return {
        background: 'red',
        color: 'lime'
      } as CSSStyleDeclaration;
    }
    

    In my understanding this should inject the background and color style to the component, but it does not...

    I can control individual style declarations like this:

    @HostBinding('style.background') private background = 'red';
    

    but I would like to do it for all of them, please help :P

    this is the full code:

    @Component({
      selector: 'my-app',
      template: `
        <div>
          <h2>Hello world!</h2>
        </div>
      `,
    })
    export class App {
    
      // This works
      @HostBinding('style.color') private color = 'lime';
    
      /* This does not work
      @HostBinding('style')
      get style(): CSSStyleDeclaration {
        return {
          background: 'red'
        } as CSSStyleDeclaration;
      }
      */
    
      constructor() {}
    }
    

    and a working plunker: https://plnkr.co/edit/CVglAPAMIsdQjsqHU4Fb?p=preview

  • Ben Taliadoros
    Ben Taliadoros about 6 years
    The plunker says /* this does not work */, any update
  • Günter Zöchbauer
    Günter Zöchbauer about 6 years
    Copying to a new Plunker would probably do to get the Angular version updated. I'll have a look when I have a bit of time (no guarantees)
  • Thilak Rao
    Thilak Rao about 6 years
    @BenTaliadoros Demo was broken. Fixed it.
  • Thilak Rao
    Thilak Rao about 6 years
    @GünterZöchbauer Yes, here you go - stackblitz.com/edit/style-hostbinding-demo
  • Zengineer
    Zengineer almost 5 years
    How can you set multiple definitions for the same style, e.g. cursor: grab; cursor: -webkit-grab
  • Günter Zöchbauer
    Günter Zöchbauer almost 5 years
    I don't think you can. Better to set/clear a class and use CSS instead.