繁体   English   中英

Angular:从父组件调用函数时出错

[英]Angular: Error when calling function from parent component

我正在尝试从我的角度应用程序中的父组件调用子组件的功能,但出现错误

在我的父组件(称为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
}

这样就可以完成。

slices.component.html(父级)

           <snd-canvas #yourChild 
                        *ngIf="isCanvasOpen" 
                        [selectedSlice]="selectedSlice" 
                        [parentComponent]="parentComponent">
            </snd-canvas>

    <div *ngIf="!showSearchBar && isCanvasOpen">
        <button mat-icon-button 
                matTooltip="Save Slice" 
                (click)="CallsaveSlice()">
// CallsaveSlice() method can be called when *ngIf is true and the element will // exists in dom
                   ...icon...
        </button>
    </div>

slices.component.ts(父级)

@ViewChild('yourChild') child;

CallsaveSlice(){

    this.child.saveSlice();
}

原来这是一个非常简单的解决方案,我只需要将(click)="yourChild.saveSlice()"更改为(click)="child.saveSlice()"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM