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?
<mat-checkbox> supports an indeterminate state, similar to the native <input type="checkbox"> . While the indeterminate property of the checkbox is true, it will render as indeterminate regardless of the checked value. Any interaction with the checkbox by a user (i.e., clicking) will remove the indeterminate state.
We can toggle the checked or unchecked state of mat-checkbox using toggle() method.
The ng-focus directive tells AngularJS what to do when an HTML element gets focus. The ng-focus directive from AngularJS will not override the element's original onfocus event, both will be executed.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With