4

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

Alessandro Celeghin
  • 4,039
  • 14
  • 49
  • 95

4 Answers4

7

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.

moritzg
  • 4,266
  • 3
  • 37
  • 62
Will Howell
  • 3,585
  • 2
  • 21
  • 32
  • 1
    This is now deprecated and the new directive is called cdkFocusInitial. But do you know if this only works when using the dialog component of angular material itself or should this focus directive also work alone on any other modal component? I at least thought so since it is available in the anguluar/cdk package, but I can not get it to work with a ngbootstrap modal – Gerros Sep 25 '18 at 13:07
  • 4
    I had to double check the source, but the `cdkFocusInitial` attribute doesn't actually manage any logic. It's just there as a place-marker when using `cdkTrapFocus` – Will Howell Sep 26 '18 at 19:33
  • 1
    In order to get `cdkFocusInitial` to work outside of the Material components that have it baked in (MatDialog, MatBottomSheet, MatSidenav), it must be contained in an element that has both `cdkTrapFocus` (as per @WillHowell), and `cdkTrapFocusAutoCapture="true"` – Brian Schantz Jun 04 '20 at 16:28
0

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

FussinHussin
  • 1,718
  • 4
  • 19
  • 39
0

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

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

0

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
})
Nabel
  • 1,767
  • 14
  • 23