'How can I get the width and height of a component in angular?
I've designed a loading component for the forms input elements in my angular forms to be displayed while the fields are loaded from the api. Here, I have to provide the height and the width of the component to the app-loader component so that it can occupy space accordingly.
For now what I have done is manually use a switch-case and provide heights and widths within that. However, this is hard since I have many other input types to be developed and also it's even harder to make it responsive. My question is, is there a more efficient way to dynamically pass the height and the width of the component relevant to that particular switch case to the app-loader component?
What I have so far is shown below.
<ng-container
*ngIf="!formInput.loaded"
[ngSwitch]="formInput.type">
<div *ngSwitchCase="FORM_INPUT_TYPE.CHECKBOX">
<app-loader width="409" height="24"></app-loader>
</div>
<div *ngSwitchCase="FORM_INPUT_TYPE.IMAGE_DROP_AREA">
<app-loader width="414.66" height="96"></app-loader>
</div>
<div *ngSwitchCase="FORM_INPUT_TYPE.RATING">
<app-loader width="409" height="30"></app-loader>
</div>
<div *ngSwitchDefault>
<app-loader width="645" height="39.75"></app-loader>
</div>
</ng-container>
Solution 1:[1]
Inject the element ref of the component in the constructor like this:
...
private elem: ElementRef,
...
Then you can get the native element by this.elem.nativeElement.
Then you can get the height and width by offsetHeight and offsetWidth.
If you want a particular div, just use @ViewChild() and do the same.
Tip: Usually you will retrieve the height and width in the ngOnInit.
However, depending on your situation, you may want to do it in ngAfterViewInit, or subscribe to the scroll event with the @HostBinding() directive.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Aleksandar Angelov |
