5

I'm wondering how to get the following working in Angular 4 and Angular Material: I want to display a little tooltip when the user focusses a Material Checkbox, so I wrote the following in my Template:

<mat-checkbox (focus)="foo()">Test</mat-checkbox>

In the corresponding component the foo method simply alerts the user (just for testing):

sayHello() {
    alert('Hallo Welt');
}

It seems that I don't get focus events from the Checkbox this way. The documentation of Material Checkbox tells me:

The mat-checkbox uses an internal input type="checkbox" to provide an accessible experience. This internal checkbox receives focus and is automatically labelled by the text content of the mat-checkbox element.

So far so good, it seems that the focus event is propagated by the internal checkbox, but how do I have to modify my Template to listen to the focus event?

Btw: I've the same issue when dealing with mat-radio-button

Update 02.11.2017 I managed to find a workaround inspired by Dynamically add event listener in Angular 2. I used Renderer2 to register the deisred listener programmatically like the following:

const nativeElement = this.checkboxComponent._inputElement.nativeElement;
this.renderer.listen(nativeElement, 'focus', () => {
  this.tooltip.showTooltip();
});

This works but feels unnecessarily complicated, since I have to inject Renderer2 into the component and define a handle to the checkbox component itself via ViewChild().

I can imagine that there must be a much simpler way for this simple usecase?

Ansgar Schulte
  • 463
  • 5
  • 15

1 Answers1

4

I know this is a late answer but I stumbled upon same problem and while looking for a solution found this issue 1723.A comment here talks about the focusin and focusout.You can have your actions in focusin. Stackblitz

kal93
  • 522
  • 1
  • 9
  • 22