簡體   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