Autofocus in a modal Angular 4 doesn't work

Viewed 12048

I have to focus the input at the loading of a modal but if I use the html5 attribute autofocus it seems not working. Is it possible to make it works?

<div class="col-md-6">
 <div class="form-group label-floating">
  <label class="control-label">
    {{'ticketbundle.busroutedetail.dialog.labels.buslinename'
     | translate }}<span class="star">*</span>
   </label><input autofocus class="form-control" id="name" required
   [(ngModel)]="busRouteDetail.name" name="name" #busRouteDetailname>
 </div>
</div>

I am using angular material 2

4 Answers

If you're using the Material Dialog, you can use cdkFocusInitial to specify where you want initial focus to be.

<input cdkFocusInitial type="text">

See this EXAMPLE.

you could set a local template ref with #myInput and access the element with @ViewChild() myInput in your ts file, and in the hook ngAfterViewInit get the native element and set the focus property with this.myInput.nativeElement.focus()

another option is to build a focus directive and bind it to the focus attribute of the element like this

I am using Angular Material version 13.1.3. With the bottom sheet component, cdkFocusInitial wasn't working for me unless I set the autoFocus config option as well;

this.bottomSheet.open(BottomSheetComponent, {
  autoFocus: true
})
Related