0

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?

1 Answer 1

3

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);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

You might want to ACCEPT this answer also :)
I am trying to dynamically generate element content then measure its width afterwards though. Not sure if this answers the question fully.
@EddieLam That was not your title question but ok! I hope it helped

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.