4

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.

2
  • please, provide some code example of your current scenario, as this could be achievable in many ways Commented Aug 18, 2017 at 8:04
  • Usually you wouldn't set styles imperatively. Add styles to @Component({ styles: [...], styleUrls: [...]}). You can set/remove classes or attributes in ngOnInit() to make different parts of your styles apply depending on these classes or attributes. Commented Aug 18, 2017 at 8:06

2 Answers 2

7

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;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank for your help sir :).
4

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');
  }

1 Comment

Thank for your help sir :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.