Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject Style Declarations Using Hostbinding in Angular

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

like image 265
Andrei Voicu Avatar asked Sep 11 '17 07:09

Andrei Voicu


People also ask

What does HostBinding do in Angular?

HostBinding - Declares a host property binding. Angular automatically checks host property bindings during change detection. If a binding changes, it will update the host element of the directive. @HostBinding - will bind the property to the host element, If a binding changes, HostBinding will update the host element.

What are HostBinding () and HostListener () in Angular?

@HostBinding and @HostListener are two decorators in Angular that can be really useful in custom directives. @HostBinding lets you set properties on the element or component that hosts the directive, and @HostListener lets you listen for events on the host element or component.

What is the purpose of @HostBinding?

HostBindinglinkAngular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive.

What does the following line do in Angular 6 HostBinding ('[ class valid ]') isValid?

@HostBinding('class. valid') isValid; Binds a host element property (here, the CSS class valid) to a directive/component property (isValid).


1 Answers

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

like image 128
Günter Zöchbauer Avatar answered Oct 05 '22 12:10

Günter Zöchbauer