Search code examples
angulardata-bindingparent-childeventemitterangular-event-emitter

How to pass child output to app component containing router-outlet in Angular


I wanna emit a value from a sub component up to the app component. The component structure is like this:

index.html:

<app-root></app-root>

app.component.html:

<router-outlet></router-outlet>

app.component.ts:

@Component({
  selector: 'app-root',
  ...
})

export class AppComponent implements OnInit {

  change = false;

  ...

  getStatus(value: boolean): void {
    this.change = value;
  }

...
}

child.component.ts (gets rendered via the router outlet e.g. from URL like /child):

@Component({
  selector: 'app-child',
  ...
})

export class ChildComponent implements OnInit {

  @Output() doStuff: EventEmitter<boolean> = new EventEmitter<boolean>();

  ...

  emitStuff(): void {
    this.doStuff.emit(true);
  }
}

child.component.html:

<a (click)="emitStuff()">Click</a>

Now, where should I attach the (doStuff)="getStatus() binding?

Normally in the <app-child (doStuff)="getStatus()">, but this is not available like e.g. in a static app.component.html where somewhere the <app-child></app-child> selector is written. I just don't get it, sorry ;)


Solution

  • In the parent component, you can retrieve the instance of the current component with:

    <router-outlet (activate)="onActivate($event)" (deactivate)="onDeactivate()"></router-outlet>
    

    Then subscribe to the child's EventEmitter which is nothing more than an Observable:

    onActivate(component) {
        if(component instanceof ChildComponent) {
            this.doStuffSubscription = component.doStuff.subscribe(x => ...);
        } 
    }
    
    onDeactivate() {
        if(this.doStuffSubscription)
            this.doStuffSubscription.unsubscribe();
    }