javascript - 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 函数和其他函数出现故障的孩子出现了一堆问题。我怎样才能解决这个问题?
解决方案
为了在父组件上控制子组件的功能,您需要使用输出来实现。例如你有
假设这是您的子视图的功能,即 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
}
这将完成它。
推荐阅读
- java - 为什么用for循环逐像素绘制矩形会产生间隙?
- c++ - PostMessage/SendMessage 被应用程序阻止
- regex - Jest transformIgnorePatterns 使用什么正则表达式风格?
- flutter - Flutter 问题:将参数作为命名参数传递给 Widget 构造函数
- python - unix venv django-admin 权限被拒绝
- r - 是否可以在 flextables 中包含 $math$?
- c - XC16 将数据表放入 PSV 内存 (PIC)
- javascript - 从 index.ejs 文件提交查询以从 mongodb 集合中返回特定文档
- javascript - 自定义挂钩状态更改未更新所有组件
- android - 下载 mp3 以在 android studio 中离线使用