【问题标题】:Unable to focus on a Mat card using viewchildren Angular无法使用 viewchildren Angular 专注于 Mat 卡
【发布时间】:2019-06-26 02:54:04
【问题描述】:

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

但我不断收到错误

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

Stackblitz code

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

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?
  • @AjayReddy 检查 stackblitz 我之前放错了链接

标签: angular typescript angular-material


【解决方案1】:

首先,您必须分配视图 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

【讨论】:

  • 谢谢 `{ 阅读:ElementRef }` 对我来说是新的,他们什么时候添加的?
  • 我认为它是 angular2 附带的,但 idk 肯定是因为我从 4 开始 :)
【解决方案2】:
  1. @ViewChildren("commentCard") 中的“commentCard”应该引用某些内容,因此您需要放置组件/指令类型或模板变量。模板变量意味着您在 html-tag 中添加 #name,如下所示:

    &lt;mat-card #commentCard *ngFor="let comment of comments" tabindex="0"&gt;Comment {{comment}}&lt;/mat-card&gt;

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多