Angular 6: How to Retrieve the Child Component nested within another Child Component from the Parent Component

Is there a way to access and call specific methods of child components within a parent component? For example, if we have a ParentCmp containing two child components (with their selectors and template refs), how can we call certain methods of LoadingPanels within those child components?

ParentCmp.html: ....

<child1 #child1></child1>
<child2 #child2></child2>

ParentCmp.ts:

  @ViewChild('child1', read: ComponentRef<child1Cmp>) child1Cmp: ComponentRef<InvitationsBarComponent>;
  @ViewChild('child2') meetingsBarCmp: Child2Cmp;
...

child1Cmp.instance.loadingPnl.load(() => {....});
child2Cmp.loadingPnl.load(() => {....});

How can this be achieved?

Answer №1

Why not give this a shot:

import { Component, ViewChild } from '@angular/core';
import { Child1Component } from './child1/child1.component';
import { Child2Component } from './child2/child2.component';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild(Child1Component) child1: Child1Component;
  @ViewChild(Child2Component) child2: Child2Component;

  ngAfterViewInit() {
    this.child1.child1Method();
    this.child2.child2Method();
  }

}

Don't forget to include this in your Template:

<child1></child1>

<child2></child2>

Just a heads up: You'll have access to the Child Component Instances in the ngAfterViewInit once the view is fully loaded.


Check out this Functional StackBlitz Example for reference.

Answer №2

If you wish to execute a method in child component 2 from the parent component, you can utilize ViewChild. Here is an example to guide you through the process:

Parent Component:

import { Component, ViewChild } from '@angular/core';
import { Child1Component } from './child1/child1.component';

@Component({
  selector: 'my-app',
  templateUrl: '
        <div>
        <child1 #Child1Component></child1>
        </div>',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild(Child1Component) child1?: Child1Component;

  customMethod() {
    this.child1?.child2?.someMethodOfChild2();

  }

Child Component 1:

import { Component, ViewChild } from '@angular/core';
import { Child2Component } from './child2/child2.component';

@Component({
  selector: 'child1',
  templateUrl: '
        <div>
        <child2 #Child2Component></child2>
        </div>',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild(Child2Component) child2?: Child2Component;

}

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

What is the best way to create a fixed array of unchangeable objects?

I am trying to create a class that requires an array of objects as one of its constructor parameters, with the condition that neither the array nor the objects in it can be modified. My current approach involves using the readonly modifier along with the g ...

What is the best way to access the "document" in a vscode webview provider?

I am currently working on developing an extension for vscode that utilizes React for the interface. However, I have encountered an issue where I am unable to insert my react root component into the HTML of the webview. Despite trying various approaches, n ...

Angular binding of variable names beginning with numbers

Currently in my Angular 4 project, I am utilizing the interpolation syntax below: {{variable.24h_volume}} Upon implementation, an error is thrown stating: Unexpected token '0.24' at column 5 in [{{variable.24h_volume}}] in ng:///AppModule/Comp ...

The data stored in the variable cannot be accessed when calling it in a different method

Within my component, there are several methods including constructor(){...} and ngOnInit(){...}. I have declared a variable named values:any=[] in the class, and it is initialized with JSON data within a method called getData(). getData(){ this.service. ...

Utilizing ngx-bootstrap Modal for Data Transfer to Component

I am currently dealing with an array called drivers in my component. When a button is clicked in the component, it triggers a ngx-bootstrap modal to display the fullname value from the drivers array. Now, I am looking for a way to retrieve the selected nam ...

Is it possible to utilize a mat-checkbox in place of a mat-label?

I'm attempting to build a mat-form-field with a checkbox that, when checked, will enable the form field. I believe this can be achieved through CSS adjustments, but I wonder if there is a simpler solution that I might be overlooking. <mat-f ...

Attempting to call a function with a template variable is not allowed

@Component({ selector: 'modal', ... }) export class SimpleModal { modalOpen: boolean; isModalOpen(): boolean { return this.modalOpen; } } <modal #modalRef> <div *ngIf="modalRef.isModalOpen()">...</div> </mo ...

experimenting with a TypeScript annotation

I have created a simple decorator that can trigger either stopPropagation() or preventDefault() based on certain conditions. I have thoroughly tested this decorator in my application and am confident that it works correctly. However, I encountered an issue ...

What strategies can I use to address the issue of requiring a type before it has been defined?

Encountered an intriguing challenge. Here are the types I'm working with: export interface QuestionPrimative { question : string; id : string; name : string; formctrl? : string; formgrp? : string; lowEx ...

Neglectful TypeScript null checks overlooking array.length verification

When TypeScript is compiled with strict null checks, the code snippet below does not pass type checking even though it appears to be correct: const arr: number[] = [1, 2, 3] const f = (n: number) => { } while (arr.length) { f(arr.pop()) } The comp ...

Troubleshooting problems with resolving deeply nested promises

My approach to utilizing promises has been effective until now. The issue arises when the console.log(this.recipe) returns undefined and console.log(JSON.stringify(recipes)) displays an empty array. This suggests that the nested promises may not be resolvi ...

How to pre-select a value in Angular PrimeNG dropdown on initialization

I am facing an issue with my PrimeNG dropdown in the dashboard page of my app. I want the dropdown to have a value selected when the page loads, specifically the current financial year. However, the current setup is not working as expected. Below is the co ...

Callback for dispatching a union type

I am currently in the process of developing a versatile function that will be used for creating callback actions. However, I am facing some uncertainty on how to handle union types in this particular scenario. The function is designed to take a type as inp ...

Adjusting the background color of the custom input range thumb when the input is disabled

I've customized the input thumb on my range slider, and I'm looking to change its color when it's disabled. I attempted adding a class to the thumb like this: input[type=range]::-webkit-slider-thumb.disabled and also tried adding the disa ...

What is the best way to pass form values from child components to parents when utilizing a value accessor implementation?

What is the most effective method to retrieve the values of a child component control group from a parent component? I have currently implemented this using value accessor, but I am curious about the best approach. You can check out the plunker demo I have ...

Unlocking the Power of Authorization Code Grant with PKCE in Angular6+ Applications

Seeking guidance on how to implement the MSAL library in Angular 6+ applications for integration with AZURE AD. After reviewing Microsoft's documentation, I discovered two flows: the 'implicit grant flow' and the 'auth code flow'. ...

In what ways can enhancing the TypeScript type system with additional restrictions help eliminate errors?

Encountered issues while working on my TypeScript project due to errors in the type definitions of a library. The solution was to enable the strictNullChecks flag. It seems counter-intuitive that adding restrictions can eliminate errors, when usually it&a ...

Grunt is your go-to resource for instructions on executing these tasks before the main program

Before launching my app, I need to make sure a specific grunt task is executed first: node app.js I'm having trouble finding information on how to automatically run and complete a Grunt task before initiating a node command. In particular, I have T ...

Generate an array of identifiers from a pre-existing array

I am facing a challenge where I need to create an array of IDs for each element in an existing array whose size is unknown. The twist here is that every set of four elements should have the same ID. As an illustration, if the original array (let's ca ...

Variability in Focus Behavior while Opening a URL in a New Tab with window.open()

Here is a code snippet I have been using to open a URL in a new tab: window.open(urlToOpen, '_blank', 'noopener noreferrer'); The issue I am experiencing is that when this code is executed for the first time, it opens the URL in a new ...