Angular 2 - Initiating a function in a child component from its parent

While it's common to send data from a parent component to a child using @Input or call a method on the parent component from the child using @Output, I am interested in doing the opposite - calling a method on the child from the parent. Here is an example of what I have in mind:

@Component({
  selector: 'parent',
  directives: [Child],
  template: `
<child
  [fn]="parentFn"
></child>
`
})
class Parent {
  constructor() {
    this.parentFn()
  }
  parentFn() {
    console.log('Parent triggering')
  }
}

And for the child component:

@Component({
  selector: 'child',
  template: `...`
})
class Child {
  @Input()
  fn() {
    console.log('triggered from the parent')
  }

  constructor() {}
}

The scenario here is like making a "get" request to get updated status information from the child component.

I understand that achieving this through a service and Subject/Observable is possible, but I'm curious if there's a more direct approach available.

Answer №1

@ViewChild is a useful solution, although the provided documentation may be confusing at first glance. Here is a simpler explanation that helped me grasp it better.

Imagine we have a ChildComponent with a method:

whoAmI() {
  return 'I am a child!!';
}

Now, let's create a parent component where we can access the method above using the '@ViewChild' technique:

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

import { ChildComponent } from './child.component';

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

export class AppComponent implements OnInit {

  @ViewChild(ChildComponent) child: ChildComponent;

  ngOnInit() {
    console.log(this.child.whoAmI()); // Output: I am a child!
  }
}

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

Angular is set up to showcase every single image that is stored within an array

I am having trouble displaying the images from the "image_url" array using a for loop. The images are not showing up as expected. Here is the content of the array: image_url: [ 0: "https://xyz/16183424594601618342458.5021539.jpg" 1: "https://xyz/1618342459 ...

Utilizing AngularJS to dynamically bind input to a value with a filter and keep it updated

I'm facing an issue with an input element linked to an object property along with a filter. Even though I update the object.field programmatically, the displayed value in the input does not change, although the correct value is reflected in the DOM In ...

How can I transform this imperative reducer into a more declarative format using Ramda?

I am currently working with a reducer function that aggregates values in a specific way. The first argument is the aggregated value, while the second argument represents the next value. This function reduces over the same reaction argument, aggregating th ...

Implement an interface with a specific number of properties in TypeScript

I am attempting to create a custom type that defines an object with a specific number of key-value pairs, where both the key and value are required to be numbers. Here is what I envision: type MatchResult = { [key: number]: number; [key: number]: numbe ...

Displaying dates with suffixes (st, rd, and th) in expression using Angular 2/4/5

How can we appropriately add suffixes (st, rd, and th) to dates in Angular 2/4/5 and beyond using the "Angular way"? For instance, displaying dates like February 25th, March 1st, April 2nd within an Angular expression {{item | date: ???}} The documentati ...

Update the child component whenever there are changes in the variables of the parent component in Angular 2

I've implemented a MasterComponent that loads the header, footer, sidebar, and more. The header includes a dropdown with options that are set once the user logs in. I need the header to remain constant even when navigating to different routes, each lo ...

Exploring the latest whatwg-fetch update with TypeScript version 2.5.3

Within my TypeScript project, I am currently utilizing "whatwg-fetch": "2.0.3" as the latest version of this polyfill. Additionally, for types, I am using version "@types/whatwg-fetch": "0.0.33", and everything functions smoothly when working with TypeScri ...

Contrasting importing a module in app.module versus a component

Angular 5 Can you explain the distinction between importing a module in app.module versus importing it directly into the component where it is needed? In particular, why is it necessary for a module to be included in node modules, app.module, the import ...

Is there support for TypeScript in express-openid-connect?

Is there any documentation available for using express-openid-connect with TypeScript, or if it is supported at all? ...

Troubleshooting a Typescript issue with "padStart" while attempting to add an object to an array

In my code, I define an object template with empty values for publishedDate, Url, and Title: let dataTemplate = { publishedDate: "", Url: "", Title: "", } dataTemplate.publishedDate = xml.chi ...

Experimenting with retrieving input from other components while implementing setTimeout

In continuation of the previous question (linked here), I am still working on tutorials for Angular testing using the same files. The current issue revolves around the setTimeout function. Within both ngOnInit and ngAfterViewInit, I have included a setTim ...

Using Angular 2, you can pass an object as a parameter to a function

Is there a way to pass an object as a parameter in the DOM on this forum? Within my HTML code, I have the following: <div class="list-items"> <ul> <li *ngFor="let i of item"> <span (click)="onAdd({{newUser.us ...

Issue transferring information between non-related components in an Angular 8 application unrelated to BehaviorSubject

Encountering an issue with passing data between unrelated components using Services and BehaviorSubject. The problem arises when the data is received, as the value of the variable Behavior arrives empty (""), despite the components having no apparent conne ...

Dealing with the "expect" HTTP header in an Express application

I'm currently developing an Express application that is responsible for handling certain low-level HTTP processing tasks. This includes dealing with requests that have various Expect headers aside from the expected value of 100-continue. Initially, I ...

The condition has been violated: It is not permitted to utilize <withRouter(Sidebar) /> in a context that is not within a <

I have encountered an error while trying to create a reactjs component and using it in another tsx file. The error I get is: Invariant failed: You should not use outside a Here is the code snippet that is causing the issue. You can also view my codesandb ...

When working with Material-UI and TypeScript, the type '{ children: never[]; }' does not share any properties with the type 'IntrinsicAttributes'. This can lead to incompatible types error messages in your code

As a beginner in TypeScript, I am attempting to incorporate an existing component, specifically tabs from material-ui. Here is the code in SimpleTab.ts: import React from 'react'; import { makeStyles, Theme } from '@material-ui/core/styles ...

I need to show the value of A$ in a React form input, but ensure that only the numerical value is

I'm currently facing an issue where I want to show the currency symbol A$ in an input field. <form [formGroup]="incomeForm" *ngFor="let field of incomeFields"> <mat-form-field fxFlex> <input matInput [value]="incomeForm ...

Transform text into clickable URL references

I have developed a unique component in NextJS that transforms a specified string within a text into a link of my choosing. export const StringToLink = ({ href, initialText, stringToReplace, useAnchorTag = false, }: { initialText: string; string ...

Updating the status of various sections with Redux toolkit

Is it possible to update the state of a store, which consists of multiple slices, with a new state in React using Redux Toolkit? While you can revert the entire store to its initial state using extraReducers, is it also possible to change the state to som ...

Having issues with inline conditional statements in Angular 5

There is a minor issue that I've been struggling to understand... so In my code, I have an inline if statement like this: <button *ngIf="item?.fields?.assetType !== 'tool' || item?.fields?.assetType !== 'questions'">NEXT< ...