首页 > 解决方案 > Angular:从父组件调用函数时出错

问题描述

我正在尝试从我的 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 函数和其他函数出现故障的孩子出现了一堆问题。我怎样才能解决这个问题?

标签: javascriptangularangular-components

解决方案


为了在父组件上控制子组件的功能,您需要使用输出来实现。例如你有

假设这是您的子视图的功能,即 html

<div (click)="saveAll()></div>

然后在子组件中从角核心导入事件发射器

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

现在在导出类之后写这个。

@Output() saveData: EventEmitter<any>; // An output event emitter variable

constructor() {
    this.saveData = new EventEmitter<any>(); // instantiate the Event Emitter
}

saveAll() {
    this.saveData.emit('') // Pass the object of the data you want to save or alter, could be a string or anything depending on the type assigned to the EventEmitter
}

然后在您的父视图中添加编辑此代码并添加输出

<snd-canvas #yourChild 
        *ngIf="isCanvasOpen" 
        [selectedSlice]="selectedSlice" 
        [parentComponent]="parentComponent"
        (saveData)="saveData($event)">

至此你有了你的函数,简单地调用你父组件中的函数

saveData(res) {
console.log(res); // You can console log it to see the passed data
}

这将完成它。


推荐阅读