Cross-component communication in Angular

I'm currently developing a web-based application using angular version 6.

Within my application, there is a component that contains another component as its child. In the parent component, there is a specific function that I would like to invoke when a button in the child component is clicked.

To illustrate the structure of my components, please refer to this image:

https://i.stack.imgur.com/JFxAc.jpg

After some research, it seems that the solution lies with the use of the Angular @Output decorator. However, I am still having trouble implementing it effectively.

Here is how my code has been organized:

Parent Component - component.ts file

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

@Component({
  selector: 'app-teacher-home',
  templateUrl: './teacher-home.component.html',
  styleUrls: ['./teacher-home.component.scss']
})
export class TeacherHomeComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  formView: boolean = false;

  toggleForm(){
    this.formView = !this.formView;
  }
}

Parent component - component.html file

<div>
    <child-compnent></child-compnent>
</div>

Child component - component.html file

<div>
    <button>Toggle Form view</button>
</div>

I am seeking assistance on how to properly call the toggleForm() function from the parent component when the button in the child component is clicked.

Answer №1

Here's an interesting article you should read: Understanding @Output and EventEmitter in Angular

Let's take a look at the child component:

@Component({
  selector: 'app-child',
  template: `<button (click)="sendToParent('hi')" >sendToParent</button> `
})
export class AppChildComponent {
  @Output() childToParent = new EventEmitter;

  sendToParent(name){
    this.childToParent.emit(name);
  }
}

Now, let's move on to the parent component:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  toggle(){
    console.log('toggle')
  }

}

Here's the HTML code for the parent component:

<app-child (childToParent)="toggle($event)"></app-child>

If you want to see this implementation in action, check out the live DEMO.

Answer №2

Here are a couple of methods to accomplish this:

  1. One option is to establish an event within the child component and assign it a callback function, similar to the following:

    @Output('eventTrigger') buttonClicked = new EventEmitter();

Use buttonClicked.emit() to trigger the event when needed.

On the parent side, you can implement it like this:

<div>
    <child-component (eventTrigger)="performAction()"></child-component>
</div>
  1. Alternatively, you can create a shared service that contains shared functions and data for both components.

Answer №3

To ensure proper functionality, you can utilize the @Output decorator within your child component and trigger an event when a button in the child component is clicked.

For example:

ChildComponent.html

<div>
    <button (click)="handleChildButtonClick()">Toggle Form View</button>
</div>

ChildComponent.ts

export class ChildComponent {
  @Output() toggleEvent: EventEmitter<any> = new EventEmitter<any>();

  ...
   handleChildButtonClick() {
     this.toggleEvent.emit(true);
   }
  ...
}

Parent Component

<div>
    <child-component (toggleEvent)="handleFormToggle()"></child-component>
</div>

Answer №4

One way to handle event listening in Angular is by utilizing the built-in EventEmitter.

app.component.ts

handleButtonClick($event) {} 

app.component.html

<div>
    <child-compnent  (buttonClicked)="handleButtonClick($event)" ></child-compnent>
</div>

child.component.ts

@Output() buttonClicked: EventEmitter<any> = new EventEmitter<any>();

onButtonClick(){
  this.buttonClicked.emit('clicked');
}

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

Determine changes in data retrieved from a JSON file using React

I've been working on a cryptocurrency app using React and a JSON API to fetch the latest data. My approach involves using fetch to load the JSON API and setInterval to refresh the app every 10 seconds. Now, I'm wondering if there's a way to ...

Tips on positioning content beneath a fixed header or navigation bar when viewed in a web browser

Hi, I'm having an issue with creating a fixed header using HTML and CSS. When I set my header to be in a fixed position, it covers up the content below it. I want the content to be positioned under the header when the page is loaded. Additionally, I&a ...

The data remains stagnant even after employing the onDataChange function in react native following the integration of a reusable component

My reusable Text input component is not working properly for validation. I am unable to retrieve the input value as it always shows null. This is how I am retrieving the username and password: <LoginTextBox placeholderName='Email& ...

Is there a way for me to verify if I have already made an AJAX data request

I have an image gallery with thumbnails. When a user clicks on a thumbnail, an ajax request is fired. I want to prevent the ajax request from firing again if the user clicks on the same thumbnail and instead use the existing data. $.getJSON(url, function( ...

response cannot be generated outside of the db.query function

router.get('/details/(:id)', (req, res) => { let vehicle_base; db.query("select b.name, count(b.name) AS total_vehicles from base AS b, vehicle AS v where b.id = v.base_id AND b.fleet_id = " + req.params.id , function(err, result){ ...

Collaborate on an Angular2 codebase for both a web application and a hybrid application

I am considering creating a mobile app based on my existing Angular2 web app codebase. After researching, I have found two possible options - Ionic2 and NativeScript. Upon further investigation, it appears that both Ionic2 and NativeScript have their own ...

Identifying whether a webpage has integrated Google Analytics

I am working with a node server. I provide a Url in the request and utilize cherio to extract the contents. My current goal is to identify whether the webpage uses Google Analytics. How can I achieve this? request({uri: URL}, function(error, response, bod ...

I am unable to give back an item

I am working with an object structure that looks like this: const obj = { name: 'john', children: [ { name: 'Foo' }, { name: 'Bar', children: [ { name: 'Doe' ...

Despite calling this.setState to update my state, the render() method is still displaying the previous values

class EditLocation extends Component { constructor(props) { super(); this.state = { LocationId: '', locationOptions: [], } this.baseState = this.state; this.findLocationById = this ...

javascript get the value of the text field

Is there a way to calculate even and odd numbers using a text field for entering the range of values and a select tag to choose between even and odd? How can I retrieve the value from the text field in order to pass it to the calculation function? Custom ...

Creating a precise regular expression for route length in Express JS

Currently, I am facing an issue while setting a route in my application. I want the URL parameter to be exactly 2 characters long, but unfortunately, the following code snippet is not producing the desired result: app.all('/:lng{2}?',function (r ...

For an unknown reason, I am facing difficulties in using the Storage feature from @angular/fire in ANGULAR 16

Recently I started exploring Angular/Fire and decided to test out some of its features by creating a basic app. Firestore and authentication were working smoothly, but when I attempted to include Storage, an error message popped up: ERROR FirebaseError: ...

How can progress bars be animated using CSS or JavaScript?

I am currently working on creating a progress bar animation, but I'm unsure whether to use CSS or JS. Can anyone provide insight on how this effect was achieved here? I am hoping to replicate it. Does anyone know if this is the code they used? I&apos ...

Using keys dynamically fetched from a JSON array file to enhance d3js functionality

I am looking to dynamically retrieve keys from an external JSON array and utilize them in d3js functions to create bar charts. Below is the JSON code provided: [ { "Interns": 5, "Projects": 10, "Time":"Jan" }, { "Interns": 16, "Pr ...

I am constantly encountering this issue: Uncaught TypeError - It's impossible to read properties of undefined (specifically 'image') in PromptCard at PromptCard.jsx on line 37

Click here to see the error message This is the code for my components\PromptCard.jsx file: "use client"; import { useState } from "react"; import Image from "next/image"; import { useSession } from "next-auth/reac ...

Develop a TypeScript class that includes only a single calculated attribute

Is it advisable to create a class solely for one computed property as a key in order to manage the JSON response? I am faced with an issue where I need to create a blog post. There are 3 variations to choose from: A) Blog Post EN B) Blog Post GER C) Bl ...

Is there a way to modify this JavaScript code so that it can function with a

I have developed a unique audio player that plays random sections of different songs. Currently, it is hardcoded for one song with three intros, a midsection, and three outros. I am looking to create a system where a list of songs can be randomly chosen fr ...

Nested SetTimeout function fails to execute

Attempting to implement a button that provides feedback for its actions, I am faced with a challenge in Angular. After sending a put request to the server, the button's state changes to show this action. Upon receiving a response, the button's st ...

Testing the use of rxjs fromEvent in Angular while mocking subscriptions

In the Angular component, I have an array of objects representing companies that are provided via @Input(). Upon loading this data, which is obtained from an HTTP request, I assign it to another variable called filteredList, which is used in an *ngFor dire ...

Updating the $location variable from the $rootScope perspective

I am facing an issue with my web app which is built using AngularJS. I have two functions in my code - one declared on the $rootScope and the other on the $scope. The code snippets are shown below: app.js app.run(function ($rootScope, $location) { $roo ...