0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.