无法使用 viewchildren Angular 专注于 Mat 卡

dot*_*pro 2 typescript angular-material angular

我正在尝试关注垫卡列表中的特定卡

但我不断收到错误

无法读取未定义的属性“焦点”

闪电战代码

应在单击按钮时添加金色轮廓

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();

  }

}
Run Code Online (Sandbox Code Playgroud)

Ant*_*sss 9

首先,您必须分配视图 id 以显示您要查询的元素

<mat-card #commentCard *ngFor="let comment of comments" tabindex="0">Comment {{comment}}</mat-card>
Run Code Online (Sandbox Code Playgroud)

下一个:MatCard还没有,nativeElement所以你必须获取元素引用

@ViewChildren("commentCard", { read: ElementRef }) 
Run Code Online (Sandbox Code Playgroud)

你已经完成了

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