Search code examples
modal-dialogangular-materialangular-dartkeyup

AngularDart Detect Keyup Event within Component


I'm trying to detect esc/enter key presses within a material-dialog modal. Here's the minimum setup:

Template:

<modal [visible]="true">
    <material-dialog info headered class="dialog">
        TEST
    </material-dialog>
</modal>

Component:

import 'dart:html';

import 'package:angular/angular.dart';
import 'package:angular_components/angular_components.dart';

@Component(
  selector: 'confirm-purchase-dialog',
  styleUrls: ['confirm_purchase_dialog.css'],
  templateUrl: 'confirm_purchase_dialog.html',
  directives: const [
    MaterialDialogComponent,
    ModalComponent,
  ],
  providers: const [overlayBindings]
)
class ConfirmPurchaseDialogComponent {

  @HostListener('keyup', ['\$event'])
  void onKeyUp(KeyboardEvent e) {
    print("KEYUP");
  }
}

I've also tried @HostListener('keyup'), but no luck. Totally stuck, would really appreciate suggestions.


Solution

  • Popups (including dialogs) are re-parented to another place in the DOM so as to handle z-indexing issues. Thus you won't get events from the dialog in the host. Instead you can add events directly to material-dialog instead:

    Template:

    <modal [visible]="true">
        <material-dialog info headered class="dialog" (keyup)="onKeyUp">
            TEST
        </material-dialog>
    </modal>
    

    Component:

    import 'dart:html';
    
    import 'package:angular/angular.dart';
    import 'package:angular_components/angular_components.dart';
    
    @Component(
      selector: 'confirm-purchase-dialog',
      styleUrls: ['confirm_purchase_dialog.css'],
      templateUrl: 'confirm_purchase_dialog.html',
      directives: const [
        MaterialDialogComponent,
        ModalComponent,
      ],
      providers: const [overlayBindings]
    )
    class ConfirmPurchaseDialogComponent {
    
      void onKeyUp(KeyboardEvent e) {
        print("KEYUP");
      }
    }
    

    Note: This is only going to capture keyboard events when the focus is in the dialog itself. You might want to add a event on the body instead to catch all keyup instances. This you would need to do with just general 'dart:html'