繁体   English   中英

无法使用Viewchildren Angular专注于Mat卡

[英]Unable to focus on a Mat card using viewchildren Angular

我正在尝试着眼于垫卡列表中的特定卡

但我不断出错

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

Stackblitz代码

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

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

  }

}

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

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

下一步: MatCard没有nativeElement因此您必须获取元素引用

@ViewChildren("commentCard", { read: ElementRef }) 

你完成了

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

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

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

  2. 您还需要告诉@ViewChildren您想要获取DOM元素而不是Angular组件,例如@ViewChildren("commentCard", { read: ElementRef }) commentCardList: QueryList<ElementRef>;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM