BaoBao
BaoBao

Reputation: 299

Angular set css style for :host in ngOnInit

I don't know how to set css style for :host {} in ngOnInit in component. Can use Renderer to set this?

Example:

<app-a *ngFor ="let a in alist" [a] = "a"></app-a>

In ngOnInit app-a i wanna to set width height style by percent for :host of app-a component when in rendered by ngFor?

Can I do it?

Many Thanks.

Upvotes: 4

Views: 3568

Answers (2)

yurzui
yurzui

Reputation: 214057

You can also use @HostBinding decorator like:

import { Component, HostBinding } from '@angular/core';  

@Component({
  selector: 'my-app',
  templateUrl: `./app.component.html`
})
export class AppComponent {
  @HostBinding('style.display') display: string;
  @HostBinding('style.width.%') width: number;
  @HostBinding('style.height.px') height: number;

  ngOnInit() {
    this.display = 'block';
    this.width = 50;
    this.height = 500;
  }
}

Upvotes: 7

Max Koretskyi
Max Koretskyi

Reputation: 105497

You usually set styles in a declarative way in the component decorator:

@Component({
   styles: [':host { display: block; }']
});
export class AppComponent {}

But if you really need to do that from ngOnInit, you can insert the host element and use renderer:

export class AppComponent {
  constructor(private host: ElementRef, private renderer: Renderer2) {  }

  ngOnInit() {
    this.renderer.setStyle(this.host.nativeElement, 'display', 'block');
  }

Upvotes: 4

Related Questions