Call child component method from parent class - Angular

Cover Image for Call child component method from parent class - Angular
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

Call child component method from parent class - Angular

Are you struggling with calling a child component method from the parent class in Angular? Don't worry, you're not alone! This situation can be a bit tricky, but once you understand the concept, it becomes much easier. 😊

Let's dive into the code provided to understand the problem and find a solution.

The Problem

In the code snippet you provided, you have a parent component, AppComponent, and a child component, NotifyComponent. The issue is that when you invoke the callMethod() in the parent component, it only fires the console.log() line and doesn't set the test property.

Understanding the Issue

The problem here is that you're creating a new instance of the NotifyComponent in the parent component using this.notify = new NotifyComponent();. This means that the child component instance in the parent component is not the same as the one being rendered in the template.

The Solution

To fix this issue and properly call the child component method from the parent class, you need to establish a communication channel between the parent and child components. There are several ways to achieve this, and I'll show you one of the simplest and most commonly used methods: using ViewChild.

  1. Import the ViewChild decorator from @angular/core in the parent component.

import { Component, ViewChild } from '@angular/core';
import { NotifyComponent } from './notify.component';
  1. Use ViewChild to bind the child component to a property in the parent component.

@ViewChild(NotifyComponent)
private notify: NotifyComponent;
  1. Update the submit() method in the parent component to call the child component method using the notify property.

submit(): void {
    // execute child component method
    this.notify.callMethod();
}

With these changes, you'll be able to properly invoke the callMethod() function and set the test property in the child component.

Final Code

Here's the modified parent component code:

import { Component, ViewChild } from '@angular/core';
import { NotifyComponent } from './notify.component';

@Component({
    selector: 'my-app',
    template:
    `
    <button (click)="submit()">Call Child Component Method</button>
    `
})
export class AppComponent {
    @ViewChild(NotifyComponent)
    private notify: NotifyComponent;

    constructor() { }

    submit(): void {
        // execute child component method
        this.notify.callMethod();
    }
}

And the child component code remains the same:

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

@Component({
    selector: 'notify',
    template: '<h3>Notify {{test}}</h3>'
})
export class NotifyComponent implements OnInit {
    test: string;

    constructor() { }

    ngOnInit() { }

    callMethod(): void {
        console.log('successfully executed.');
        this.test = 'Me';
    }
}

The Call-to-Action

Congratulations! You've learned how to properly call a child component method from the parent class in Angular. Now it's time to put your newfound knowledge into action. Go ahead and try implementing this solution in your own Angular app. If you have any questions or run into any issues, feel free to leave a comment below. Happy coding! 👩‍💻🚀


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello