Utilizing Angular: Harnessing the Power of Template Reference Variables to Invoke Child Methods

Trying to utilize a template reference variable to call a method from a parent component to child component. Here's the attempted approach:

File: navigation.component.html

<button type="button" class="btn btn-primary relative waves-light" (click)="CartTable.loadCart()" mdbWavesEffect>My Cart</button>

<app-cart-table-modal #CartTable></app-cart-table-modal>

File: cart-table-modal.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-cart-table-modal',
  templateUrl: './cart-table-modal.component.html',
  styleUrls: ['./cart-table-modal.component.scss']
})
export class CartTableModalComponent implements OnInit {

  constructor() {   }

loadCart(){
 console.log('load cart called');
}
}

Encountering an error message:

ERROR TypeError: jit_nodeValue_5(...).loadCart is not a function

Any suggestions on how to resolve this error would be greatly appreciated. Thank you in advance.

Answer №1

To invoke a public method from a child component, you can utilize the @ViewChild() decorator.

child.component.ts

export class ChildComponent implements OnInit {

  constructor() {   }

  method1(){
    console.log('I have been logged!');
  }

}

parent.component.html

<div>
    <button (click)="onLogged()">Log Me!</button>
    <child-comp #childComp></child-comp>
</div>

parent.component.ts

export class ParentComponent implements OnInit {

  @ViewChild(ChildComponent) child_component: ChildComponent;

  constructor() {   }

  onLogged(){
    this.child_component.method1();
  }

}

For further information on Component interaction, visit angular.io.

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

Tips for tracking pages when navigating to a new one?

Whenever I try to navigate to a new tab using the controller with this code snippet: this.nav.push(EditPage); The new tab seems to disappear. How can I prevent it from disappearing? Image reference below: https://i.sstatic.net/kkC0C.png Expected resul ...

Typing in a number will always activate the change event

Having trouble with Angular's change event on numeric input? It doesn't always trigger when clicking the increment or decrement buttons - it only triggers once and then requires the input to lose focus before triggering again. Is there a way to ...

Combining Multiple ReactJS Elements in a Single DIV using TypeScript (TSX)

Looking at the code snippet provided, I am attempting to display three elements or components within the same container. I have experimented with utilizing the Render function for each element, however it appears that the last component replaces the first ...

I am encountering an issue retrieving data in React using TypeScript

Here is the code snippet I am working with: type State = { ... PromotionIDs: Number[]; autoAdjustUsage: AutoAdjustUsage[] }; const InitState: State = { ... PromotionIDs: [], autoAdjustUsage: [] }; const contracts = this.state[PointsTable ...

Dealing with nullable objects in Typescript: Best practices

Looking for a solution to have a function return an object or null. This is how I am currently addressing it: export interface MyObject { id: string } function test(id) : MyObject | null { if (!id) { return null; } return { ...

Develop Connective Plugins using Angular 12

I am working on implementing a new feature for my app that involves storing certain modules on the backend and loading them dynamically based on user demand. Instead of loading all modules at once, I want to only load the necessary modules just before the ...

What can be done to ensure that the singleton is prepared for the other components?

I have run into a particular issue: I am trying to develop a singleton class that stores the client configuration. The configuration needs to be fetched from an SQL server via an ASP.net API. Let's consider a scenario where the Home component utilize ...

Angular integrates a user-friendly help file feature that includes helpful information and instructions for

I am looking to streamline my code by storing help text in a separate file using key value pairs. This will allow me to easily reference them next to form labels on different components. To achieve this, I have created an app-config.ts file and utilized @ ...

Enable lazy loading to retrieve the current routed module

I'm currently working on a way to exclude a component when a specific module is routed in a lazy loading application. For instance, in my AppComponent I have a router-outlet and a component above it: <div> <my-component></my-compo ...

I am having trouble retrieving the FormGroup in my nested Angular reactive form from the parent component

After watching Kara Erickson's demo of Angular forms at AngularConnect 2017 on YouTube, I was intrigued by her explanation of nested reactive forms. The issue I encountered was that no matter what I tried, I kept getting a null parentForm. Below is a ...

Accessing environment-based constants in TypeScript beyond the scope of Cypress.env()Is there a way to gain access to environment-specific constants

Imagine I have an API test and the URL and Credentials are different between production and development environments: before("Authenticate with auth token", async () => { await spec().post(`${baseUrl}/auth`) .withBody( { ...

Different TypeScript parameters that cannot be used together

Consider the given JavaScript function below: function x({foo, fooId, bar, barId}) {} I am looking to refactor this function into TypeScript in such a way that the caller is required to provide either foo or fooId, but not both. The same rule should apply ...

Angular error: Trying to subscribe to an undefined property

As I dive into my inquiry, it's important to mention that despite conducting extensive research, I have yet to uncover a solution or explanation for the error I am encountering. I must also emphasize that I am a complete novice when it comes to Angul ...

Avoid activating automatic save feature in Material UI data grid

After creating a data-grid and attempting to add records, I encountered an issue where pressing the TAB key automatically saved the data when focusing on the save button without manually pressing enter. How can this behavior be prevented so that manual con ...

formik connects props that are lacking certain properties

Trying to figure out a way to simplify the process of declaring all the properties of formik in my Props when using connect(). The error message I keep encountering is: Type '{ entry: Entry; }' is missing the following properties from type &apos ...

Angular meets Material Design 3

Recently, I've delved into the realm of material design and have been exploring the compatibility of Material Design 3 with Angular version 17. After following the guidelines outlined in Material Design 3, I managed to successfully install it. Howeve ...

Sorry, Computed styles are not available in IE 11 Edge DevTools

Currently facing an issue with a component element rendering differently on IE11, however the DevTools for both IE and Edge aren't showing any CSS in the Styles or Computed tab. What is the correct way to debug this situation? Comparison from left to ...

Is it possible to retrieve a trimmed svg image and store it on a device using react-native-svg in React Native?

I have a modified image that I want to save in my device's gallery. Can someone please guide me on how to achieve this? My project is developed using TypeScript. Modified image: https://i.stack.imgur.com/LJOY9.jpg import React from "react"; ...

Ways to initiate a language shift in the **JavaScript yearly calendar** when the language is modified in an Angular application

1. I have incorporated ngx-translate into my Angular application for translation purposes. 2. I have successfully implemented the ability to switch languages during initialization by specifying options like {language:'ja'} for Japanese within th ...

It seems that change detection is triggered by a click event regardless of the detachment setting

My understanding of Angular 2 change detection may be off, but I expected that if a component's ChangeDetectionStrategy was set to Checked, CheckOnce or Detached, the component would only check for changes once upon instantiation. However, it seems to ...