Accessing the Component Host Element Via Constructor Injection | Task

Ole Ersoy
Feb - 04  -  1 min

Scenario

We wish to know the height and width of our HelloComponent host element.

Approach

Get the host element via constructor injection:

@Component({
    selector: 'hello',
...
export class HelloComponent{
    constructor(private hostElement: ElementRef) {}
ngOnInit() {
    const styles = getComputedStyle(this.hostElement.nativeElement);
    console.log("Height", styles.height);
    console.log("Width", styles.width);
}

Demo