Steve Nginyo
Steve Nginyo

Reputation: 301

How to send output from component via router-outlet to parent component

I need to emit a string when Parent page

<div class="container-fluid fluidy">
     <router-outlet (currentpage)="componentAdded($event)"></router-outlet>
</div>

Parentpage.ts

  componentAdded(stringer){
    console.log(stringer);
    this.currentpage = stringer;
  }

Child page

  @Output() currentpage = new EventEmitter<string>();

  ngOnInit(): void {
    this.currentpage.emit('profile');
  }

Upvotes: 1

Views: 116

Answers (1)

Aakash Garg
Aakash Garg

Reputation: 10979

If a component is launching inside router-outlet, its no more a child component of component having router-outlet. hence normally having output on router-outlet tag will not work. Instead you can do something like

Parent component html

<router-outlet (activate)="componentActivated($event)" (deactivate)="componentDeactivated($event)"></router-outlet>

Parent component ts

componentAddedSubscription: Subscritption;
componentActivated(component) {
    if(component instanceof ChildComponent) {
         this.componentAddedSubscription = component.currentpage.subscribe(res=>{
              //your logic
         });   
    }
}

componentDeactivated(component) {
   if(component instanceof ChildComponent) {
         if(this.componentAddedSubscription?.unsubscribe) {
             this.componentAddedSubscription.unsubscribe();
         }
   }
}

Upvotes: 3

Related Questions