Search code examples
dartangular-dart

document:click not working


I'm trying to make a global click event directive. But document:click does not work for me.

import 'package:angular/angular.dart';

@Directive(
  selector: '[clickOutside]'
)
class ClickOutsideDirective {

  @HostListener('click', [r'$event.target'])
  void onClick(targetElement){
    print('Target:' + targetElement.toString());
  }
}

When changing document:click to click I get expected behavior. But of course not globally. What am I doing wrong?


Solution

  • The document: and similar event scopes were removed in Dart.

    Use instead

    import 'dart:html';
    
    class ClickOutsideDirective implements OnInit, OnDestroy {
      StreamSubscription _docClickSub;
      ngOnInit() {
        _docClickSub = document.onClick.listen((event) {
          print('Target:' + event.target.toString());
        });
      }
    
      ngOnDestroy() {
        _docClickSub?.cancel();
        _docClickSub = null;
      }
    }