Triggering an event from a higher-level component to a lower-level component

Within the parent component named personDetails, there is a Submit button. This parent component contains multiple child components called person`. Each time I click on the Submit button, I need to trigger a method within the child component.

Is it possible to send an event from a parent component to a child component using @Output?

In most cases, events are emitted from child to parent components. However, in this scenario, I require a way to access a value specific to the child component, which necessitates emitting an event from parent to child.

Answer №1

To facilitate communication between a parent and child component in Angular, you can create a shared service where you define an Observable. This Observable can be subscribed to from the child component, allowing you to take action when receiving values from the parent.

//communication.service.ts

import { Injectable, Inject } from '@angular/core';
import { Subject }    from 'rxjs/Subject';
@Injectable()
export class CommunicationService {
  private notification = new Subject<any>();
  
  /**
   * Observable streams for notifications
   */
  notificationObservable$ = this.notification.asObservable();

  constructor(){}

  public notifyChild(data: any) {
    if (data) {
      this.notification.next(data);
    }
  }
}

//parent.component.ts

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

import { CommunicationService } from './communication.service';

@Component({
  selector   : 'parent-component',
  templateUrl : './parent.component.html'
})
export class ParentComponent implements OnInit, OnDestroy {
  constructor( private communicationService: CommunicationService ){
  }

  ngOnInit() {
    this.communicationService.notifyChild({message: 'Hello from parent'});
  }
}

//child.component.ts

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

import { CommunicationService } from './communication.service';

@Component({
  selector   : 'child-component',
  templateUrl : './child.component.html'
})
export class ChildComponent implements OnInit, OnDestroy {
  private subscription: Subscription;
  
  constructor( private communicationService: CommunicationService ){
  }

  ngOnInit() {
    this.subscription = this.communicationService.notificationObservable$.subscribe((res) => {
      if (res.hasOwnProperty('message')) {
        console.log(res.message);
        // perform additional actions here

      }
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

Answer №2

Child Component

In childComponent.ts

@Input() private uploadSuccess: EventEmitter<boolean>;

Furthermore, inside childComponent.ts, be sure to subscribe to the event:

ngOnInit() {
  if (this.uploadSuccess) {
    this.uploadSuccess.subscribe(data => {
      // Implement childComponent actions after receiving event from parent.
    });
  }
}

Parent Component

In ParentComponent.html

<app-gallery  [uploadSuccess] = "uploadSuccess" > </app-gallery>

In ParentComponent.ts

private uploadSuccess: EventEmitter<boolean> = new EventEmitter();

onImageUploadSuccess(event) {
   console.log('Image Upload success');
   if (event.code === 'OK' && this.maxUploadLimit > 0) {
      this.galleryImagesCount = this.galleryImagesCount + 1;
      this.maxUploadLimit = this.maxUploadLimit - 1;
    }

   // Parent triggers the event that was initially passed as an `@Input` variable to the child-component
   this.uploadSuccess.emit(true);
}

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

Unexpected lint errors are being flagged by TS Lint in Visual Studio Code out of nowhere

After a 5-week break from VS Code and my computer due to vacation, I was surprised to see TS lint errors popping up out of nowhere. These errors were completely incorrect and appearing in files that had previously been error-free. It's as if the linte ...

When zooming out, Leaflet displays both tile layers

I'm currently working on integrating two tile layers along with a control for toggling between them. Below is the code snippet I am using: const layer1: L.TileLayer = L.tileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', { ...

Exploring methods for efficiently handling extensive XLSX files in a Node.js environment

Currently, I am utilizing the ts-xlsx library on the server side to read data. The process involves reading data from the frontend as a byte array using file-reader and then sending this byte array to a library to process the data. However, in cases where ...

Error: Reference to an undeclared variable cannot be accessed. TypeScript, Cordova, iOS platforms

Can anyone offer some advice on what might be the issue? I'm encountering an error while building my Ionic app on the IOS platform, but everything is running smoothly on Android. ReferenceError: Cannot access uninitialized variable. service.ts:31 O ...

How can I achieve this using JavaScript?

I am attempting to create a TypeScript script that will produce the following JavaScript output. This script is intended for a NodeJS server that operates with controllers imported during initialization. (Desired JavaScript output) How can I achieve this? ...

Verify the type of email domain (personal or corporate)

Here's an example: isPersonalEmail("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0aea1ada580a7ada1a9aceea3afad">[email protected]</a>") // true isPersonalEmail("<a href="/cdn-cgi/l/email- ...

Typescript Declarations for OpenLayers version 6

The package @types/openlayers found at https://www.npmjs.com/package/@types/openlayers only provides type definitions for version 4.6 of OpenLayers. This is clearly stated in the top comment within the file index.d.ts. If types for OpenLayers 6 are not av ...

Is it possible to manipulate an Object within Object typescript?

My recent project involved working with React and Typescript to fetch data from an API. Once the data is fetched, it is saved as an object called coin. However, I encountered a situation where the data may not be fully loaded, resulting in coin being null. ...

What is the process of creating a for loop in FindById and then sending a response with Mongoose?

Is there a way to get all the data in one go after the for loop is completed and store it in the database? The code currently receives user object id values through req.body. If the server receives 3 id values, it should respond with 3 sets of data to th ...

Encountering a surprise token < while processing JSON with ASP.NET MVC alongside Angular

I encountered an issue when attempting to return the Index page. The data is successfully sent from the client to the server, but upon trying to display the Index page, an error occurs. Could someone review my code and identify where the mistake lies? acc ...

What are the steps to implement the `serialport` library in `deno`?

After tinkering with Deno to extract readings from an Arduino, I encountered a roadblock when it came to using the serialport library correctly. Here is what I attempted: According to a post, packages from pika.dev should work. However, when trying to use ...

Dealing with routing problems within sub-routes using Angular 2 and Express, attempting to serve content from sub-folders

I am currently using Express to serve a local Angular2 application. To enable the Angular2 app to access various node_modules from Express, I have set up the following configuration: config.dependencies = [ { staticPath: './node_modules/@angular/&a ...

What benefits do declaration files offer compared to sources in TypeScript?

When developing and releasing a library using TypeScript, there are 2 approaches: One option is to generate declaration files d.ts along with the bundled JavaScript file and then specify it in package.json with: "types": "./dist/mylib.d.ts" Alternativel ...

What is the best way to connect a toArray function to an interface property?

Consider the following scenario: interface D { bar: string } interface B { C: Record<string, D> // ... additional properties here } const example: B = { C: { greeting: { bar: "hi" } } // ... additional properties here } Now I would like t ...

I attempted to implement a CSS and Typescript animation for a sliding effect, but unfortunately, it isn't functioning

So I'm encountering an issue with this unique ts code: {/* Mobile Menu */} <div className="lg:hidden"> <button className="flex items-center w-8" onClick={toggleMenu}> {isMobileMenuOpen ? ( ...

Issue with Angular's BeforeLoginService causing route authorization to fail

Implementing Route Authorization in Angular-12, I have the following service: BeforeloginService: import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; i ...

Preserve your NativeScript/Angular ImagePicker choice or retrieve the complete file path

After choosing an image with the Image Picker, I get a content// URL content://com.android.providers.media.documents/document/image%3A139 However, when using ImageSource.fromAsset(), I receive an empty object. My main objective is to save this image as a ...

Retrieve Json data from an external API in Angular by utilizing the HttpClient module

Being a novice in angular, I am experimenting with fetching data from an external API. Although I managed to retrieve the data successfully on the console, I encountered errors when attempting to display it on the screen. Below are the details of my setup: ...

"After updating to version 3, the Ionic 3 component's JavaScript is failing to refresh properly

During the development of my Ionic 3 app, I encountered what I believe is a cache issue. It seemed to be related to lazy loading components as the problem arose after upgrading to v3 and activating lazy loading. While in development mode and using ionic se ...

rxjs in Angular2 is missing the observable.interval function

Currently, I am attempting to utilize the interval method of an observable; however, I consistently encounter the following error message: Property 'interval' does not exist on type 'Observable<any>'. I have included the follow ...