Carolina
Carolina

Reputation: 250

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?

Upvotes: 2

Views: 10162

Answers (1)

Get Off My Lawn
Get Off My Lawn

Reputation: 36341

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

Upvotes: 5

Related Questions