How to call a function within a component from another component without encountering the "Cannot read property" error

Having trouble calling a function from one component in another by passing the reference of one to the other. I keep getting a "Cannot read property" error. Below is the code snippet

Alert Component

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

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

export class AlertComponent implements OnInit {  
  AlertMessage:string;

  constructor() {        
   }

  showSuccessAlert(){       
      this.AlertMessage =  "Data saved successfully.";
  }

  ngOnInit() {
  }

}

Alert component html

<p>{{AlertMessage}}</p>

Attempting to call showSuccessAlert function from another component

Component

import { Component, OnInit, Input, HostListener } from '@angular/core';
import { QueueService } from 'src/services/queue.service';
import { ActivatedRoute } from "@angular/router";
import { NgForm } from '@angular/forms';
import { Queue } from 'src/models/queue';
import { error } from 'util';
import { AlertComponent } from '../alert/alert.component';

@Component({
  selector: 'queue-edit',
  templateUrl: './queue.edit.component.html'  
})
export class QueueEditComponent implements OnInit{
    @Input() alert:AlertComponent;

    queue = new Queue();    
    constructor(private api: QueueService, private route: ActivatedRoute){
        this.route.params.subscribe(params => this.params = params);

    } 
    title = "Edit Support Queue";

    ngOnInit() { 
    }

    @HostListener('saveQueue')
    saveQueue(queue){
        this.alert.showSuccessAlert(); 
    }
}

html

<app-alert></app-alert>

ERROR

ERROR TypeError: Cannot read property 'showSuccessAlert' of undefined
    at QueueEditComponent.push../src/app/queue/queue.edit.component.ts.QueueEditComponent.saveQueue (queue.edit.component.ts:44)
    at Object.eval [as handleEvent] (QueueEditComponent.html:25)
    at handleEvent (core.js:19545)
    at callWithDebugContext (core.js:20639)
    at Object.debugHandleEvent [as handleEvent] (core.js:20342)
    at dispatchEvent (core.js:16994)
    at core.js:17441
    at HTMLButtonElement.<anonymous> (platform-browser.js:993)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
    at Object.onInvokeTask (core.js:14051)

Answer №1

Consider utilizing @ViewChild rather than @Input. Here's an example:

import { ..., ViewChild } from '@angular/core';
...
import { AlertComponent } from '../alert/alert.component';

@Component({...})
export class QueueEditComponent implements OnInit{
    @ViewChild(AlertComponent) alert:AlertComponent;

    ...

    @HostListener('saveQueue')
    saveQueue(queue){
        this.alert.showSuccessAlert(); 
    }
}

PS: Remember that you won't have access to the AlertComponent in the QueueEditComponent until ngAfterViewInit is called. Be sure to ensure that your saveQueue function is called after ngAfterViewInit.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble getting Vuejs to work when appending an element to Fullcalender

Hi there, I am facing an issue where appending a custom button to a full calendar event is not working properly with Vue.js methods. It works fine with core JavaScript, but I really want it to work with Vue.js methods. Any ideas on how I can achieve this? ...

What is the method for obtaining the div ID's from this form?

This is the scenario I am working on: my app takes the text inputted by the user and exports it to a specific website that contains similar elements. For example, if the user enters a title in the app and clicks a button, the app will transfer that value t ...

What is the reason for being unable to remove the event listener from a sibling element?

function show1() { console.log("ok1"); document.getElementById("a2").removeEventListener("click", delegate); } function show2() { console.log("ok2"); } function show3() { console.log("ok3"); } function delegate(event) { var flag = event.target ...

Storing the data object in an array using Angular and Mongoose in Node.js

I've encountered an issue with my Angular form connected to Node JS and MongoDB. While some data from the form gets saved in mongoDB, there are certain fields like measurementUsed and testTolerance that do not get saved properly. This is how my model ...

I am working with an array of objects in React JavaScript, and I need to find a way to convert it into

Currently, I am in the process of creating this JavaScript function: export function convertArrayObjToFileDownload(data, filename, filetype = 'application/octet-stream') { const blob = new Blob(data, { type: filetype }); downloadBlob(blob ...

Tips on utilizing the Material Ui Select input property?

Trying to understand why material-ui's InputBase is functional while regular HTML input is not. The documentation defines the input prop as follows: An Input element; does not have to be a material-ui specific Input. Successful example: import Sele ...

Is there a way to clear the list after each input is made?

Looking for help with the Ping Pong Test. Whenever I click Start and enter a number, it just keeps adding to the list. How can I make it reset the list after each input? $(document).ready(function() { $("#Start").click(function() { ...

Setting the font-size in HTML/CSS to dynamically adjust and fill the entire width and height of its

I'm trying to make a <div> element adjust its size based on the browser window. Within this <div>, there is a paragraph of text: <div style="width:80%; height:80%; margin:10%;"> <p>Paragraph of text. Paragraph of text. Pa ...

What is the method for eliminating PHP $_SESSION using AJAX?

I am facing an issue with removing an array within a PHP Session variable using AJAX. Here is the process I follow: HTML: <a href="#" onclick="delete_pix(false, '1', false, '1.jpg');">remove</a> JavaScript: functio ...

AJAX chat application's updating frequency

As I work on building a website that includes a feature for real-time chatting between users (similar to Facebook chat), I have implemented a system where messages are stored in a MySQL table called messages. This table contains the message ID, sender ID, ...

Encountering an issue with Apollo Express GraphQL: Error message stating that the schema must have distinct type names, yet it contains more than one type named "DateTime"

After importing the applyMiddleware library from 'graphql-middleware' to add validation middleware on mutation's input, I created a sample middleware function that logs the input. export const logInput = async (resolve, root, args, context, ...

What is the best way to retrieve a collection of DOM elements in JSX?

I'm in need of rendering certain components only if a specific condition is met. To achieve this, I have written the following inside the render() method: return ( <div className={classes.root}> {registrationScreen && ( * ...

Equivalent of ResolveUrl for loading scripts without the need for server technology

I am in the process of converting an ASP.NET web page into a plain HTML web page. Most of the work is done, however, I am having trouble replacing the ASP.NET Page.ResolveUrl function when setting a reference to a javascript file: <script src="<%= ...

Utilize static information within an Angular component

I'm working on an Angular project in my localhost and I want to have two routed components that share the same data. One component will display the data, while the other will handle the data. In simpler terms, I need two webpages: one with an input f ...

Retrieve information from a JSON API on one server and showcase it on an HTML page hosted on a different server

I have a situation where I need to transfer data from one project (Project1) to another project (Project2). To achieve this, I decided to convert the Project1 data stored in a database into a JSON API and then call it using an HTML page from Project2. Howe ...

Steps for triggering a re-render in a React component when an external value changes

I am currently working on a project that involves using Meteor and React. In my code, I have a class called WebRTC which handles all WebRTC-related logic: class WebRTC { this.isCalling = false; ... } In addition to the WebRTC class, there is ...

Show the loader animation until the browser's loading icon stops spinning

My website receives a high volume of traffic and pulls data from several servers to display on the page. It typically takes 3-4 minutes for the entire page to finish loading. Here is a preview of some of the partial page data: I am looking to add a spinni ...

What sets class/instance methods apart from static methods when it comes to their functionality in applications?

As I develop APIs for my application, I've been curious about the difference between defining functionality methods like this: class Foo { static method1(req, res) {} static method2(req, res) {} } and class Foo { method1(req, res) {} method ...

Send an AJAX request to the specified `httpost` action method without any page refresh to load the

Today I have an interesting challenge that's been a brain teaser for me. While I may not be an expert in ASP.Net MVC4, I'm excited to tackle something new. The ultimate goal is to create a dynamic tree view for partial pages within a standard pag ...

Error: The function req.logIn is not valid

I'm currently in the process of creating a dashboard for my Discord bot, but I've encountered an error that reads as follows: TypeError: req.logIn is not a function at Strategy.strategy.success (C:\Users\joasb\Desktop\Bot& ...