【发布时间】:2019-11-20 07:18:37
【问题描述】:
我正在尝试从我的 Angular 应用程序中的父组件调用子组件的函数,但出现错误
在我的父组件(称为slices 组件)中,子组件是这里的 snd-canvas 组件:
<snd-canvas #yourChild
*ngIf="isCanvasOpen"
[selectedSlice]="selectedSlice"
[parentComponent]="parentComponent">
</snd-canvas>
父组件中还有一个按钮,我想调用子组件中的 saveSlice() 函数:
<div *ngIf="!showSearchBar && isCanvasOpen">
<button mat-icon-button
matTooltip="Save Slice"
(click)="yourChild.saveSlice()">
...icon...
</button>
</div>
在 slice.component.ts 我有
import { Component, OnInit, ViewChild } from '@angular/core';
@ViewChild('yourChild') child;
但是,当我单击按钮时,出现以下错误:
ERROR TypeError: Cannot read property 'saveSlice' of undefined
我认为问题可能是当切片组件加载时 isCanvasOpen 被初始化为 false,因此 snd-canvas 组件尚未呈现并且未定义。我尝试将 *ngIf="isCanvasOpen" 更改为 [hidden]="isCanvasOpen" 以修复该错误,但导致 NgInit 函数和其他函数出现故障的孩子出现一堆问题。我该如何解决这个问题?
【问题讨论】:
-
是
@ViewChild('yourChild') child;组件类的属性吗? -
是的,它的定义是这样的:
export class SlicesComponent implements OnInit{ @ViewChild('yourChild') child; ....rest of code.... } -
你试过
(click)="child.saveSlice()"。注意它不应该是yourChild而应该是child -
感谢@user2216584 修复它。
标签: javascript angular angular-components