本机元素toArray()未定义

时间:2019-05-23 01:23:36

标签: html angular typescript

我正在对正在使用的应用程序进行一些重构,但遇到了麻烦。

在我的HTML上,我有一个使用ngFor的卡片组成的网格。有一个按钮应“显示/隐藏”特定的div。

我的解决方案是使用局部变量来获取特定元素并显示该特定div。一切正常,但是现在,我无法正常工作,出现此错误:

  

错误TypeError:“ this.travelInfoBox.toArray(...)[index]未定义”   showBox card.component.ts:40      View_CardComponent_0 CardComponent.html:12

以下是父组件的HTML:

<div class="row">
    <div class="col s12 m6 l4" *ngFor="let student of students; let i = index">
        <app-card [student]="student" [i]="i"></app-card>
    </div>
</div>

这是卡片组件的HTML:

<div class="col s12 m4 l2 right">
    <hr class="hide-on-med-and-up">
    <i class="material-icons">send</i>
    <i class="material-icons" (click)="showBox(i)">access_alarm</i>
    <span class="hide-on-med-and-up card-travel-info">Tavel Information</span>
    <app-travel-info class="card travel-info s12 m6 l4" #travelInfoBox></app-travel-info>
    <hr class="hide-on-med-and-up">
</div>

TS 卡组件):

import {Component, Input, ViewChildren, QueryList, ElementRef, AfterViewInit } from '@angular/core';            

@Component({
    selector: 'app-card',
    templateUrl: './card.component.html',
    styleUrls: ['./card.component.scss']
})

export class CardComponent {
    @Input('student') student: any;
    @Input('i') i: any;
    @ViewChildren('travelInfoBox') private travelInfoBox: QueryList<ElementRef>;
    constructor() { }

    showBox(index) {
        const nativeElement = this.travelInfoBox.toArray()[index].nativeElement;
        nativeElement.style.display = nativeElement.style.display === 'none' || !nativeElement.style.display ? 'block' : 'none';
    }

}

0 个答案:

没有答案