javascriptangulardom-manipulationangular-renderer2elementref

How to measure element width of an HTML element in Angular?


I want to dynamically create an element and then get its clientWidth. The code snippet looks like this using the regular DOM API.

HTML Snippet:

<div id="non-existent-element"></div>

The element has its css property visibility set to 'hidden'.
Typescript/ Javascript snippet

let labelContainer = document.querySelector('div#non-existent-element');
labelContainer.innerHTML = `
<span>${fundName}</span>
<span> (${performance}%)</span>
`;
let children = labelContainer.children as HTMLCollectionOf<HTMLElement>
for(let i = 0; i < children.length; i++) {
  children[i].style.fontSize = fontSize + + 1 +'px';
} 
return labelContainer.clientWidth;

How can I achieve the goal using Angular's Element Ref and Renderer2 API?


Solution

  • Simple usage of clientWidth

    app.component.html

    <p #test>test is the elementRef name</p>
    

    app.component.ts

    export class AppComponent implements AfterViewInit {
      @ViewChild('test') test: ElementRef;
    
      constructor(private renderer: Renderer2) {
        //ERROR TypeError: Cannot read property 'nativeElement' of undefined
        // console.log(this.test.nativeElement.clientWidth);
      }
    
      ngOnInit() {
        //logs: 583
        console.log(this.test.nativeElement.clientWidth);
      }
    
      ngAfterViewInit() {
        this.renderer.setStyle(this.test.nativeElement, 'backgroundColor', 'red');
        this.renderer.setStyle(this.test.nativeElement, 'color', 'white');
        this.renderer.setStyle(this.test.nativeElement, 'width', '500px');
    
        //logs: 500
        console.log(this.test.nativeElement.clientWidth);
      }
    }