dh_washburn
dh_washburn

Reputation: 43

Angular 2 Event Handling and Custom Events

I am currently working on a project which involves creating a library of components in Angular 2 for app teams to use. I recently created a modal component, but I am having some accessibility issues. Specifically, I want the modal to close when a user selects the ESC key, but not if there is an internal component such as a dropdown that should consume the ESC event. With the modal structure allowing various content to be displayed via <ng-content>, it makes the situation even more difficult because I can't guarantee what will be inside of the modal.

Ideally I would like to find a way to see if a projected component is listening for the (keydown) or (keyup) events or even better, find a way to see if another component has already consumed or handled the event. I know that if I were writing an application instead of providing a library, I could add an attribute to the events inside of the projected components or create a custom event handler as described here but I unfortunately do not have those options.

Upvotes: 0

Views: 1054

Answers (1)

peng37
peng37

Reputation: 4550

What about using RxJS? In your component:

isShowModal: boolean = false;
private keyup$ = Observable.fromEvent(document, "keyup");
private keyupSubcribe: any;

ngOnInit() {
    this.keyupSubscribe = this.keyup$.subscribe((e: KeyboardEvent) => {
        if(this.isShowModal && e.keyCode === 27) {
             this.isShowModal = false;
        }
    });
}

ngOnDestroy() {
    this.keyupSubscribe.unsubscribe();
}

onShowModal() {
    this.isShowModal = true;
}

And in your template:

...
<button (click)="onShowModal($event)">Show Modal</button>
...
<your-modal *ngIf="isShowModal"></your-modal>
...

Upvotes: 1

Related Questions