Unable to focus on a Mat card using viewchildren Angular

Viewed 2453

I am trying to focus on a specific card from a list of mat cards

But I keep getting error

Cannot read property 'focus' of undefined

Stackblitz code

Should add a gold outline on click of button

import { Component, OnInit, QueryList, ElementRef, ViewChildren } from '@angular/core';

/**
 * @title Basic cards
 */
@Component({
  selector: 'card-overview-example',
  templateUrl: 'card-overview-example.html',
  styleUrls: ['card-overview-example.css'],
})
export class CardOverviewExample implements OnInit {

  comments: number[];
  @ViewChildren("commentCard") commentCardList: QueryList<ElementRef>;

  ngOnInit() {
    this.comments = [1, 2, 3, 4, 5, 6, 7, 8];
  }

  focus() {
    const elementRef = this.commentCardList.find((item, index) => index === 4);
    elementRef.nativeElement.focus();
//this.commentCardList[4].nativeElement.focus();

  }

}
2 Answers
  1. The "commentCard" in @ViewChildren("commentCard") should reference something, so you need to put either a component/directive type or a template variable. A template variable means that you add #name in a html-tag, like this:

    <mat-card #commentCard *ngFor="let comment of comments" tabindex="0">Comment {{comment}}</mat-card>

  2. You also need to tell @ViewChildren that you want to get the DOM element and not the Angular component, like this @ViewChildren("commentCard", { read: ElementRef }) commentCardList: QueryList<ElementRef>;

https://stackblitz.com/edit/angular-gu5kpe-dqua65?file=app%2Fcard-overview-example.ts

Related