Alessandro Celeghin
Alessandro Celeghin

Reputation: 4209

Autofocus in a modal Angular 4 doesn't work

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

Upvotes: 4

Views: 13928

Answers (4)

Nabel
Nabel

Reputation: 1956

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
})

Upvotes: 0

Alexandre Gombert
Alexandre Gombert

Reputation: 188

You can set ngbAutofocus on the element you want to focus.

See https://ng-bootstrap.github.io/#/components/modal/examples#focus

Upvotes: 0

Will Howell
Will Howell

Reputation: 3715

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.

Upvotes: 7

FussinHussin
FussinHussin

Reputation: 1814

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

Upvotes: -1

Related Questions