Angular 无法使用viewchildren对焦Mat卡

Angular 无法使用viewchildren对焦Mat卡,angular,typescript,angular-material,Angular,Typescript,Angular Material,我试着把注意力集中在mat卡列表中的一张特定卡上 但我总是出错 无法读取未定义的属性“focus” 点击按钮时应添加金色轮廓 import { Component, OnInit, QueryList, ElementRef, ViewChildren } from '@angular/core'; /** * @title Basic cards */ @Component({ selector: 'card-overview-example', templateUrl: 'c

我试着把注意力集中在mat卡列表中的一张特定卡上

但我总是出错

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

点击按钮时应添加金色轮廓

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

  }

}
从'@angular/core'导入{Component,OnInit,QueryList,ElementRef,ViewChildren};
/**
*@title基本卡
*/
@组成部分({
选择器:“卡概览示例”,
templateUrl:'card overview example.html',
样式URL:['card-overview-example.css'],
})
导出类CardOverview示例实现OnInit{
评论:编号[];
@ViewChildren(“commentCard”)commentCardList:QueryList;
恩戈尼尼特(){
注释=[1,2,3,4,5,6,7,8];
}
焦点(){
const elementRef=this.commentCardList.find((项,索引)=>index==4);
elementRef.nativeElement.focus();
//this.commentCardList[4].nativeElement.focus();
}
}

首先,必须指定视图id以显示要查询的元素

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

  • @ViewChildren(“commentCard”)
    中的“commentCard”应该引用某些内容,因此您需要放置组件/指令类型或模板变量。模板变量表示在html标记中添加
    #name
    ,如下所示:

    Comment{{Comment}

  • 您还需要告诉
    @ViewChildren
    您想要获取的是DOM元素,而不是角度组件,比如
    @ViewChildren(“commentCard”,{read:ElementRef})commentCardList:QueryList


  • 你的评论卡使用的是模板引用还是Id?@AjayReddy check stackblitz我之前放错了链接谢谢“{read:ElementRef}”对我来说是新的,他们什么时候添加的?我想它是angular2的,但idk肯定是我从4开始的:)
    @ViewChildren("commentCard", { read: ElementRef })