Calculate width of li element in angular

Viewed 403

I am trying to get total width of a li element

This is the jQuery code I am using to do that

var $list = $tickerWrapper.find("ul.list");
$list.find("li").each(function (i) {
    listWidth += $(this, i).outerWidth(true);
});

HTML:

<div class="tickerwrapper">
  <ul class='list'>
    <li class='listitem'>
      MON 11 APR, 2021<br>
      Data1; <br> Data1
    </li>
    <li class='listitem'>
      MON 12 APR, 2021<br>
     Data2; <br> Data2
    </li>   
    <li class='listitem'>
      MON 14 APR, 2021<br>
       Data3; <br> Data3
    </li>
    <li class='listitem'>
      MON 15 APR, 2021<br>
         Data4; <br> Data4
    </li>
    <li class='listitem'>
      MON 16 APR, 2021<br>
        Data5; <br> Data5
    </li>
  </ul>
</div>

But in angular it is not working. It gives error

2 Answers

in your template you have to refrence that element like this:

<li #myId>...</li>

in your controller you have to do as following:

@ViewChild('myId') public myId: ElementRef;

constructor() {
    ...
}

public myFunction() {
    console.debug(this.myId.nativeElement.offsetWidth);
}

Link to Stackblitz for stimulating

Steps to select an element in Angular component template:

  • Add a template reference variable to the component HTML element.
  • Import @ViewChild decorator from @angular/core in component ts file.
  • Use ViewChild decorator to access template reference variable inside the component.
  • And finally, select the element in ngAfterViewInit method by accessing the element’s nativeElement property.

Angular code

import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
  
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
   constructor() { }

  @ViewChild('myIdentifier')
  myIdentifier: ElementRef;
  
  ngAfterViewInit() {
    var width = this.myIdentifier.nativeElement.offsetWidth;
    var height = this.myIdentifier.nativeElement.offsetHeight;
   
    console.log('Width:' + width);
    console.log('Height: ' + height);
  }  

}

HTML code

<li #myIdentifier>
  
</li>
Related