Search code examples
angularangular-materialangular-material2

How to set same md-checkbox focus outline for all focus sources


When md-checkbox is focused using keyboard, there's outline around it. But when focus is set programmatically, there is no visual indicator. Is there any way to make it look the same? enter image description here


Solution

  • Ripple is a click/focus event. If you want to have the ripple effect after setting the checkbox programmatically, you need to focus the element from your code. For that you also need to add a reference for your control.

    In your template, add a reference variable to your checkbox e.g. customCheckbox:

    <md-checkbox [(ngModel)]="checked" #customCheckbox>Check me!</md-checkbox>
    

    ... and in your code, you need to call focus() method on this control:

    // Import MdCheckbox in your ts file
    import { MdCheckbox } from '@angular/material';
    
    // Declare customCheckbox in your class
    @ViewChild('customCheckbox') private customCheckbox: MdCheckbox;
    
    // Use this line to focus the checkbox programmatically where you want.
    this.customCheckbox.focus();
    

    Link to working demo.