document.querySelector in Angular Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of document.querySelector in Angular without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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'
      )
    )
  }
}

We are here to answer your question about document.querySelector in Angular - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji