Search code examples
cssangularinputfocus

How do we use the input:focus selector in angular 2+ component?


I have a form that contains something like the following:

<div class="form-field">
<input-component [tabIndex]="tabData.tabEnable"></input-component>
</div>
<div class="form-field">
<input [tabIndex]="tabData.tabEnable" matInput cgiPrecision type="number"/>
</div>

In the css I have this:

input:focus {
border: $border-width solid $darkblue
}

but the border only shows on the input element and not the input-component component which has an input wrapped inside of it. How can I get the input:focus to work for the custom angular component as well?


Solution

  • Your custom component should listen for the focus event, then focus the input.

    @Component({
      selector: 'custom-input',
      template: `<input #myInput type="text" [(ngModel)]="innerValue">`,
      styles: [`
        input {border: 5px solid green; } 
        input:focus { border: 5px solid blue; }
      `]
    })
    export class CustomInputComponent implements ControlValueAccessor  {
    
      @ViewChild('myInput', {static: false}) inputCtrl;
    
      //...functions to implement ControlValueAccessor
    
      @HostListener('focus')
      focusHandler() {
       this.inputCtrl.nativeElement.focus();
     }
    }
    

    Here's a stackblitz demonstrating.