Angular: Modify parent component's field using route

Hello everyone!

I'm seeking assistance. In my Angular 10 application, I have a component called A.

Within this component, there is a <router-outlet> and routes defined in the routes.ts file.

My goal is to modify a variable (field) inside component A by clicking a button from another component named B, which is a route within the <router-outlet>. How can I achieve this?

Let's consider the following scenario:

A.component.html

<B [changeFieldOfA]="func"></B>

A.component.ts

export class A {
    foo: string = "";
    func() {
        this.foo = "bar";
    }
}

By passing a function that updates the field in component A to component B, everything works as intended.

However, how can we handle a situation like this?:

A.component.html

<router-outlet></router-outlet>

routes.ts

{path: "b", component: B}

In this case, I aim to invoke the func(), which belongs to A and modifies its field, within B. Unfortunately, using Input() is no longer feasible due to the routing constraints. Is there an alternative approach?

Answer №1

Check out the demo illustrating how to utilize a service for communication between components.

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

@Injectable()
export class ShareService  {   
  constructor() { } 

  private paramSource = new BehaviorSubject("");
  sharedData = this.paramSource.asObservable();

  setParam(param: string) { 
    this.paramSource.next(param);
  }    
}

To set data in the service:

this.shareService.setParam('Sending parameter');

To retrieve data from the service:

this.shareService.sharedData.subscribe(data => { 
  this.your_variable = data;
})

Make sure to include the service in your component's constructor as shown below:

constructor(private shareService: ShareService){}

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

Adjust the component suppliers based on the @input

If I were to implement a material datepicker with a selection strategy, I would refer to this example There are instances where the selection strategy should not be used. The challenge lies in setting the selection strategy conditionally when it is insta ...

Flipping the order of arguments in curried functions with fp-ts

I've been working with fp-ts and encountered a situation where I have a curried function consisting of two functions, like this: const newFunction = (name: string) => (greeting: string) => console.log('Hello ' + name + ' ' + ...

Angular4 is throwing an error stating that the center element in the HTML is an undefined function

Is there an alternative tag that can be used instead of <center> <\center> in angular4, as it indicates that center is not a recognized function? ...

Supabase encounters various errors during operation

I am encountering some issues while using supabase with TypeScript. Interestingly, I can see the errors in WebStorm, but not in VSCode. Can you provide any assistance? supabase .channel('custom-all-channel') .on( 'postgre ...

Managing API responses using Redux and Typescript

As a beginner in Typescript, I am struggling to integrate Redux with it. The documentation on using Redux with Typescript is confusing me. I am attempting to fetch data and dispatch it to my reducer for future use, just as I did before adopting Typescript ...

Consequences of eliminating Angular component wrapper tags from the DOM

Imagine there is a component named <hello-world> with the following HTML template: <div>Hello World!</div> When this component is used and inspected in the DOM, it shows up like this: <hello-world> <div>Hello World!</div ...

Access your account using Google authentication within an Angular framework

My latest project involves creating an API that allows users to log in with Google by using the endpoint http://localhost:3001/api/v1/user/google. Here's how it works: A user clicks on the link http://localhost:3001/api/v1/user/google The endpoint h ...

Avoid Angular 6 router from taking precedence over routes set in Express Server

What is the best way to ensure that Angular routing does not conflict with routes from an Express Node Server? In my Express server, I have set up some routes (to node-RED middleware) as follows: server.js // Serve the editor UI from /red app.use(settin ...

Error: A variable is potentially 'undefined' (ts2532), even though I have just assigned a value to it

Encountering Object is possibly 'undefined'. ts(2532) errors in TypeScript for an optional parameter, despite being clearly defined... interface Foo { keyValue?: Record<string, string> } const a: Foo = { keyValue: { key1: 'value&apo ...

Identify potential interference with Sentry.captureMessage(...) or Sentry.captureException(...) functions within a JavaScript application, such as being obstructed by an ad-blocking extension

Overview Our Javascript application uses Angular and TypeScript, with Sentry.io for error reporting. If an error occurs, a custom modal allows users to leave a message, which should be sent to Sentry when they click submit. Issue We have noticed that mes ...

Error occurs when Protractor end-to-end tests encounter a problem with browser.executeAsyncScript

I encountered an error while attempting to implement e2e testing for our application. My initial test case failed with the following error message: Failed: Error while running testForAngular: javascript error: Unexpected identifier JavaScript stack: ...

Having trouble debugging localhost because the cookie for a specific domain is not being written

In a particular scenario, I needed to write a cookie upon logging in with a code for a specific domain, for example, let's say the domain is "uat.example.com." The backend API will generate this cookie after authenticating the user, and then the appl ...

Angular is throwing an error stating that the type '{ }[]' cannot be assigned to the type '[{ }]'

I'm in need of assistance and clarification regarding the error I encountered in my application... When I receive a JSON response from an API with some data that includes an array of products, I aim to extract these products (izdelki) from the array, ...

Is there a way to establish a boundary for the forEach function in TypeScript?

In my web-based game, I use the forEach command to retrieve the team players in the lobby. However, for a specific feature in my game, I need to extract the id of the first player from the opposing team. How can I modify my current code to achieve this? T ...

The parameter 'To' cannot be assigned the argument of type '{pathname: string; shipment: TShipment;}'

Is there anyone who can assist me with a Typescript issue I'm currently facing? Upon running tsc in my project, I encountered the following error: I am getting the error saying that 'Argument of type '{ pathname: string; item: Item; }' ...

Angular is patiently waiting for the initial function to activate

I have a situation where I need to wait for the results of my first function before executing the second one. code First function getUser() { this.authService.user().subscribe( user => { this.user = user; console.log('c ...

Using setBounds in ng2-ui/map: A step-by-step guide

I have been attempting to display a map using the setBounds feature with the ng2-ui/map library. Unfortunately, I am having trouble finding documentation on how to achieve this. https://github.com/ng2-ui/map Currently, here is the code that I have writte ...

Utilize node-pre-gyp to execute the installation with the option to fallback to building and specify the static

Attempting to install an Angular App into an existing project, encountering a dependency error during npm install. After cloning the existing Angular project, I am setting up my development environment. Note that I am working behind a proxy and firewall, ...

Exploring the implementation of Generic types within a function's body

When trying to encapsulate logic inside the OrderGuard component (which can handle two types of orders: CheckinOrder or Checkout order), I encounter an issue when passing the order to the orderLoad callback in TypeScript. The error message states that "Ch ...

Chunks loaded incorrectly due to laziness

Currently, I have a successful Angular5 application integrated within an existing Java EE application, which is packaged as a WAR and contains the angular sources for my app. These sources are bundled using the command: ng build --prod --output-hashing no ...