2

Angula 11 // REMARK THIS HAPPENS WITH ALL THE OFFSETS BUT GET THE ID PER EXAMPLE WORKS

So we have a few @Viewchilds of ElementRefs that we want to get the offsetWidth.

To do that we have the following code:

// container is the REF that has the HTML --> #container
@ViewChild('container') containerRef: ElementRef;
...
...
ngAfterViewInit(): void {
const containerOffset: number = this.containerRef.nativeElement.offsetWidth;
const containerOffset1: number = (this.containerRef.nativeElement as HTMLElement).offsetWidth;
}

The problem is that the offsets that we get are 0.

But if we do a console.log(this.containerRef) it shows perfectly the nativeElement inside and you can see that the offset is different than 0.

Someone can help here please ?

( If possible a solution without using document.querySelector.....)

enter image description here

enter image description here

mmonteirocl
  • 382
  • 2
  • 16
  • Try and and get offset in setTimeout. Don't rely on console.log, printed value can and will change because it's by referencen (if it's an object). Try instead `console.log(this.containerRef.nativeElement.offsetWidth)` and it will probably be 0 again. – Bojan Kogoj Dec 02 '20 at 13:46
  • Okei, my question is why is 0, when it should be bigger like 247 ? – mmonteirocl Dec 02 '20 at 15:08
  • Because it's probably not fully rendered yet. Make a stackblitz example – Bojan Kogoj Dec 02 '20 at 15:09
  • But supposedly, all the elements that has to be accessed with @viewChild, you can access them ASAP on ngAfterInit right ?? – mmonteirocl Dec 02 '20 at 15:37

2 Answers2

0

This is how I got the width of a parent element view child for my situation. I was able to test this successfully using both "OnInit" and "AfterViewInit".

/** Left Column */
@ViewChild('gridLeftColumn', { static: true })
public gridLeftColumn: ElementRef;

const columnWidth: number = (this.gridLeftColumn.nativeElement as HTMLElement).clientWidth;

console.log('Column Width: ', columnWidth); // 760
Jason Spence
  • 472
  • 5
  • 16
0
ngAfterViewInit() {
      console.log(this.el.nativeElement.clientWidth); //return 0
  }


ngAfterViewInit() {
    setTimeout(() => {
      console.log(this.el.nativeElement.clientWidth); // return 84 (true)
    }, 100);
  }

I have a 'Directive' and I found a solution for 'Directives'. Just add a little timeout. Have a nice day!

Mustafa.psd
  • 27
  • 2
  • 9