0

everyone!

I need your help. I have a component in my Angular 10 application, let's name it A.

In this component I have <router-outlet> and also routes described in routes.ts file.

What I need is to change variable (field) inside A component by clicking button from some B component, that is route inside <router-outlet>. How can I do it?

For example, we can talk about such variant.

A.component.html

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

A.component.ts

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

Here's everything cool, cause I can pass function, that changes my A component field to my component.

But what if I have this variant?:

A.component.html

<router-outlet></router-outlet>

routes.ts

{path: "b", component: B}

I want to call this func(), that belongs to A (and changes its field) inside B, but i can't do it through Input() anymore, cause in router I can't do it.

ArthCode
  • 92
  • 9
  • I am having a difficult time understanding. is B a child component of A? Or a new routed to component? If you route to B, you are no longer viewing A so you wouldn't be able to change a variable in A. – Rick Jul 22 '20 at 17:33
  • Your question has code description. Actual code is much better. – Ruan Mendes Jul 22 '20 at 17:38
  • maybe there's some other use of angular, but shouldn't you ONLY have the router-outlet in your app.component.html file? I'm not familiar with the idea of an app having multiple router outlets. seems confusing and unnecessary – Rick Jul 22 '20 at 18:11

1 Answers1

1

Demo You can use service to communicate 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 in service

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

to get from service

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

constructors like

constructor(private shareService: ShareService  ){}
mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54