Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 4 set focus in a field of a modal

Tags:

angular

In my angular 4 project I need to focus some field inside a bootstrap-modal

This is the modal:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
    <i class="material-icons">clear</i>
    </button>
    <h4 class="modal-title">{{'checkpoint.table.dialog.title' | translate }}</h4>
   </div>
   <form #modelForm="ngForm">
  <div class="modal-body">
    <div class="row">
        <div class="col-md-8">
            <div class="form-group label-floating">

                <label class="control-label">{{'checkpoint.table.dialog.labels.name' | translate }}
                <span class="star">*</span>
                </label>
                <input class="form-control" id="name" name="name" required [(ngModel)]="checkpoint.name" #focus />

            </div>
        </div>
    </div>

I open the dialog with a normal button

<button type="button" class="btn btn-info btn-lg" 
data-toggle="modal" data-target="#myModal">Open Modal</button>

I have tried some solutions like:

@ViewChild('focus') inputElement: ElementRef;

and in the button when I open the modal:

this.inputElement.nativeElement.focus();

or:

$('#myModal').on('shown.bs.modal', function () {
      $('#focus').focus();

But in the first case the inputElement is undefined and in the second case nothing happen

like image 960
Alessandro Celeghin Avatar asked Jan 05 '18 14:01

Alessandro Celeghin


2 Answers

You will need to use setTimeOut to workout..
though it shouldn't be undefined and your code of @ViewChild('focus') looks OK, but if it does not work then try changing the name from focus to some thing else...as focus is keyword as well...

Also I suggest do not mix Jquery and Angular... Not good practice.

 setTimeout(() => {
        this.inputElement.nativeElement.focus();
 });
like image 103
codeSetter Avatar answered Nov 15 '22 22:11

codeSetter


I wrote a directive for this, with that an input field gets automatically focused when the modal opens.

import { Directive, Input, ElementRef, AfterViewInit } from '@angular/core';

@Directive({
    selector: '[focus]'
})
export class FocusDirective implements AfterViewInit {
    @Input() focus: boolean;

    constructor(private element: ElementRef) {}

    ngAfterViewInit() {
        if (this.focus) {
            this.element.nativeElement.focus();
        }
    }
}

In the html use it with:

<input type="text"
       (keyup)="search($event)"
       focus="true"
>
like image 40
Gerros Avatar answered Nov 15 '22 20:11

Gerros