sanjihan
sanjihan

Reputation: 6002

style host in Angular from component

You can style the component host in .css file using :host selector. I'd like to set the top on the component host from the component.

For example, given <app-test> </app-test>, I'd like to dynamically style host of AppTestComponent from the component itself.

Is this possible in Angular?

Upvotes: 0

Views: 65

Answers (1)

skouch2022
skouch2022

Reputation: 1161

Yes, it is possible to dynamically style the component itself. First, you will need to inject ElementRef as a dependency. Then you can access the host via this._elementRef.nativeElement.


@Component({
  //...
})
export class AppTestComponent {

  constructor(private _elementRef: ElementRef) {

    this._elementRef.nativeElement.style.color = 'red';
  }
}

BUT, this is not recommended.

First of all, it's possibly a security risks according to Angular.

It is best to have an @Input class/style that let the parent passes into app-test. This way, the app-test doesn't have to worry about the environment around it, and does more than it needs to.

Upvotes: 1

Related Questions