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?
CodePudding user response:
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.