Angular 6 - Accessing grandparent methods in grandchild components

I am in need of running the functions of the grandparent component:

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

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

  public loginPage = true;

  public login = function(){
    this.loginPage = false;
  }
  public logout = function(){
    this.loginPage = true;
  }
  
}

using this grandchild component as a medium:

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

@Component({
  selector: 'app-dropmenu',
  templateUrl: './dropmenu.component.html',
  styleUrls: ['./dropmenu.component.css']
})
export class DropmenuComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

  logout(){
    sessionStorage.removeItem('token');
    **//EXECUTE LOGOUT() GRANDPARENT FUNCTION HERE**
  }
}

I found an example using a DataService like this one to achieve something similar:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject('default message');
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

However, I do not want to pass any message, but simply execute a function. Is it necessary to create a DataService for this purpose? Can't I directly implement an Observable or something similar in the grandparent component? If so, could someone please provide an example?

Answer №1

After some trial and error, I finally found a solution to the issue at hand.

To tackle the problem, I devised a DataService that acts as an intermediary between the child component and the grandparent component. This DataService receives the button click event from the child, converts it into an observable, and allows the grandparent to subscribe to this subject in order to monitor changes and trigger the corresponding function in the grandparent component.

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/internal/Subject';
import { Observable } from 'rxjs';

@Injectable()
export class DataService {

    private subject = new Subject();

    constructor() { }

    sendClickEvent() {
        this.subject.next();
    }

    clickEvent(): Observable<any>{
        return this.subject.asObservable();
    }

}

Child component:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service'

@Component({
  selector: 'app-dropmenu',
  templateUrl: './dropmenu.component.html',
  styleUrls: ['./dropmenu.component.css']
})
export class DropmenuComponent implements OnInit {

  constructor(private dataService: DataService) { }

  ngOnInit() {
  }

  handleEvent(){
    this.dataService.sendClickEvent();
  }

}

Grandparent component:

import { Component } from '@angular/core';
import { DataService } from '../app/services/data.service'

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

  constructor(private dataService: DataService){
    this.dataService.clickEvent().subscribe(response => { this.handleEvent() });
  }

  public loggedIn = true;

  public handleEvent = function(){
    sessionStorage.removeItem('token');
    this.loggedIn = false;
  }
}

I believe this approach can be beneficial for others facing similar challenges.

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

Sometimes encounter undefined values after assigning them through the service

One of the challenges I am facing is handling public fields in my service: @Injectable() export class ShareDataService { // Some code public templateForCurrencyCOS; public templateForPercentCOS; public templateForCurrencyCOGS; public te ...

Is there a way to transfer a variable from Angular 2 Frontend Express JS to an Angular 2 component?

After conducting thorough research, I have made specific modifications to my code. However, I am encountering some errors in my console that I cannot seem to resolve. Despite following a tutorial step by step. Your assistance would be highly valued as I a ...

Tips for adjusting the color of sorting arrows in the Header of a Data table using Angular Material

I'm having trouble changing the header color of the sorting arrows in the Angular Material data table. You can view the data table here. Currently, the sorting arrows are gray by default and I want to change them to white. Despite my efforts, I haven ...

Validation of dynamic fields in a reactive form is malfunctioning specifically for the <Select> element

My form includes a reactive form with a form array, where clicking a button adds a new form group to the array. Upon form submission, I want to validate if these dynamic fields are empty. However, room.errors?.required does not seem to execute as expected ...

Having trouble with NextJS TypeScript and the randomUUID?() function? If you're seeing the error TS2386 that says "Overload signatures must all be

In my project setup, I have a mono-repo structure utilizing Lerna for managing 2 NextJS projects and 1 shared project. I recently attempted to integrate typescript. The NextJS projects seem to be functioning correctly (following the documentation), but I ...

Navigate to the main page of the routing module within Angular

I’m struggling to find an easy way to achieve this task. Here is a snippet from my app-routing.module.ts file: { path: 'items', loadChildren: () => import('./items/items.module').then(m => m.ItemsModule) }, And in items-routi ...

The property functions normally outside the promise, but is undefined when within the promise context

I am currently working on filtering an array based on another array of different objects but with the same key field. Although I have made some progress, I keep encountering errors that I am unable to resolve. @Component({ selector: 'equipment&ap ...

Ways to display a popup when hovering over a marker in ngx-mapbox-gl

I have a current implementation that displays markers and popups on click of markers. We now need to update it to show popups on hover instead. Here is the structure of my template: <mgl-map #map1 [style]="'mapbox://styles/mapbox/streets ...

Mastering the art of filtering arrays in RxJS 6 using Observables and async functions

I am currently working with an Observable that returns data and is being bound asynchronously in HTML. Here is where I make the service call: this.ProductOptions = this.ProductService.fetchProduct(); The HTML binding looks like this: Productoptions | a ...

Utilizing the Querystring in place of semicolons: A beginner's guide

Currently, I have been working on developing an internal tool specifically designed for developers utilizing Angular2 beta 15, backed by a C# WebApi. As new versions of Angular2 are released, I ensure to upgrade accordingly. While I have incorporated rou ...

Angular Dynamic Alert Service

Is it possible to customize the text in an Angular Alert service dynamically? I'm looking to make certain words bold, add new lines, and center specific parts of the text. Specifically, I want the word "success" to be bold and centered, while the rest ...

If the value is null, pass it as is; if it is not null, convert it to a date using the

I am currently facing an issue regarding passing a date value into the rrule plugin of a fullCalendar. Here is the snippet of code in question: Endate = null; rrule: { freq: "Daily", interval: 1, dtstart: StartDate.toDate ...

Utilizing Angular 7 to extract data from the initial column of an Excel spreadsheet and store it within an array

Currently, I am in the process of uploading an excel file that contains an ID column as its first column. My goal is to extract all the IDs and store them in an array for future data management purposes. To accomplish this task, I am utilizing the XLSX l ...

Linking to a file within an npm package

Is it possible to reference local files within an npm package? Will these references still work correctly when the package is installed by a different consumer? For example, let's say I have developed an npm package for Angular which includes some HTM ...

What is the best way to reset a dropdown list value in angular?

Is there a way to erase the selected value from an Angular dropdown list using either an x button or a clear button? Thank you. Code <div fxFlex fxLayout="row" formGroupName="people"> <mat-form-field appearance=&quo ...

In the event that you encounter various version formats during your work

Suppose I have a number in the format Example "1.0.0.0". If I want to increase it to the next version, it would be "1.0.0.1" By using the following regex code snippet, we can achieve this perfect result of incrementing the version to "1.0.0.1": let ver ...

Error encountered while exporting TypeScript module

While I am working with Angular, TypeScript, and Gulp, my module system is CommonJS. However, I encountered an error when trying to import a module into my main.ts file: Error: Cannot find external module 'modules.ts'. Here is the snippet from ...

What is the best way to enable `child_process.execFile` to utilize an existing running application?

I am currently developing an Electron app that is designed to launch another application, such as Photoshop, using child_process.execFile. However, I have encountered an issue where if Photoshop is already running when child_process.execFile is called, a n ...

What is the best way to merge the data from a resolver into a combineLatest function?

I'm facing an issue with my resolver that returns an Observable<Product[]> on a page to load data. After that, I try to combine this stream with another using combineLatest. However, the problem arises when combining the streams as I receive an ...

What strategies can I implement to stop Iframes from disrupting the browser's history when interacting with them?

In my particular situation, I utilize Iframes to display Grafana on my page, which showcases beautiful and user-friendly graphs. After examining, I noticed that interactions like zooming in or out on the graph using mouse clicks trigger a type of refresh ...