Search code examples
angularcomponentsparameter-passingeventemitter

Passing data from child to parent component in angular via <router-outlet>


In app.component.html I have

<div>
    <app-login (un)="doSth($event)"></app-login>
</div>
<router-outlet (un)="doSth($event)"></router-outlet>

and in app.component.ts I have

export class AppComponent {
  title = 'order';
  uname = 'guest';

  doSth (name:any) {
    console.log("name", name);
    this.uname = name;
  }
}

The problem I have is that I get data to app.component.ts when I use tag <app-login>, but not when I use tag <router-outlet>. Why is that and how do I fix that?


Solution

  • I don't think that the router can do this.

    What you would need to send messages across your application would be a state management store like NgRX. But to make things simple you could also have a singleton subject where each one interested can subscribe to.

    Example: messaging.service.ts

    @Injectable({ providedIn: 'root' })
    export class MessagingService {
      public messages$ = new Subject();
    }
    

    app.component.ts

    export class AppComponent {
      title = 'order';
      uname = 'guest';
    
      constructor(readonly messaging: MessagingService) {
        messaging.messages$.subscribe(event => {
          this.doSth(event);
        }
      }
    
      doSth (name:any) {
        console.log("name", name);
        this.uname = name;
      }
    }
    

    login.component.ts (and all the components you want in your router-outlet:

    export class LoginComponent {
      constructor(private readonly messaging: MessagingService) {}
    
      iWantAppComponentToDoSth() {
         messaging.messages$.next({ name: 'foo' });
      }
    }