Home > Software design >  Detect if parent element binds to child's @Output in Angular
Detect if parent element binds to child's @Output in Angular

Time:08-30

I was wondering if, for example, you have an angular component like this

@Component({
    selector: 'app-child',
    ...
})
export class ChildComponent implements OnInit {
    @Output() previous = new EventEmitter<void>();

    ngOnInit() {
       // Detect if parent is listening for `previous` events
    }
}

I can detect the differences (inside the child component) between the following two use cases:

<app-child (previous)="onPrevious"></app-child>

and

<app-child></app-child>

What I would like to achieve with this is that I like to determine if I should show a previous button or not. If no one is listening for it, I can hide it. If this is not possible, I can of course add an @Input() showPreviousButton.

CodePudding user response:

Since EventEmitter extends the RxJS's Subject, then, I think you can use the Subject.observed read-only property to check if the parent is subscribed to it or not.

ngOnInit() {
  // Detect if parent is listening for `previous` events
  if (this.previous.observed) {
    // The parent is listening for `previous` events
  }
}
  • Related