document.querySelector in Angular

I have a list where each li has unique data-id.

<ul class="list">
  <li class="list__el"
      *ngFor="let item of cars"
      data-id="{{ item.id }}">
  </li>
</ul>

In JS I would wrote

let myLi = document.querySelector(`.list__el[data-id="${item.id}"]`)

How to correctly rewrite it for Angular?

Answer

Use @ViewChildren and a template reference such as #listItem.

@Component({
template: `<ul class="list">
  <li #listItem class="list__el"
      *ngFor="let item of cars"
      data-id="{{ item.id }}">
  </li>
</ul>`
})
export component MyComponent implements AfterViewInit {

  // Note that the parameter here relates to the #listItem in the template.
  @ViewChildren('listItem')
  public listItems!: QueryList<ElementRef<HTMLLIElement>>

  public ngAfterViewInit() {
    console.log(
      this.listItems.find(itm => 
        itm.nativeElement.getAttribute('data-id') === 'my-element-id'
      )
    )
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *