1

I need to display rectangles with text inside them, all above some specific words of a text. To know the size of the rectangle to display, I need to know de length (in pixels) of the word above of which the rectangle will be.

I know it's possible to know the length of a string in JavaScript/JQuery, but I'd like to know if it's possible to do it natively in Angular 6.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Possible duplicate of [How do I retrieve an HTML element's actual width and height?](https://stackoverflow.com/questions/294250/how-do-i-retrieve-an-html-elements-actual-width-and-height) – zmag Mar 21 '19 at 15:29

1 Answers1

3

the "angular" way to do this is with the ViewChild(ren) decorator.

view child:

in html tag your element:

<span #widthTarget>my text</span>

in controller:

@ViewChild('widthTarget')
widthTarget: ElementRef;

ngAfterViewInit() { //view children must be accessed at this hook or later
  console.log(this.widthTarget.nativeElement.width);
}

for multiple elements, use the ViewChildren decorator with it's associated functions.

You could also pull this off with a directive of some kind but it depends on your actual use case.

bryan60
  • 28,215
  • 4
  • 48
  • 65
  • Great solution! I only had to change the "width" attribute to "offsetWidth", as with "width" I was getting "undefined" as result. The precision of the width is acceptable, as it doesn't include the decimal fraction. Thanks! – Gabriel Candia Mar 22 '19 at 19:51
  • the property used depends on the width / display setting of the element. clientWidth is usually a good option as well. – bryan60 Mar 22 '19 at 20:41