A
A
Ann20162017-03-13 08:57:07
Angular
Ann2016, 2017-03-13 08:57:07

How to set focus on an input element?

How to set focus on input in angular? Been playing all weekend, nothing comes out.
I got acquainted with this question access to the element , but this option does not start for me.

<form #formVar="ngForm" (ngSubmit)="getPlaceInQueue(formVar.value)">

            <div class="row">
                <div class="form-group col-md-12">
                    <label for="name-input" class="col-md-2 col-form-label">ФИО</label>
                    <div class="col-md-12">
                        <input class="form-control focus-input" type="text" value="" id="name-input" name="name" required #name = 'ngModel' ngModel placeholder="Введите ФИО">
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="form-group col-md-12">
                    <label for="example-tel-input" class="col-md-2 col-form-label">Телефон</label>
                    <div class="col-md-12">
                        <input class="form-control" type="tel" value="" id="example-tel-input" name="phoneNumber" placeholder="Введите номер телефона"
                               required minlength="15" #phoneNumber = 'ngModel' ngModel [textMask]="{mask: phoneNumberMask, guide: false}">
                    </div>
                </div>
            </div>
            <button class="btn btn-success btn-lg col-md-12 btn-block" [disabled]="formVar.form.invalid">Получить талон</button>
        </form>

I need to set the focus to the full name, but nothing comes out for me ..

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Yarkov, 2017-03-13
@Ann2016

Why didn't the autofocus attribute suit you?

A
Artem, 2017-03-21
@free_doom

I would rather use FormBuilder and ReactiveForms

<form [formGroup]="loginForm" (ngSubmit)="onSubmitLoginForm()" novalidate>
   <input formControlName="userLogin" #userLoginInput type="email">
   <input formControlName="userPassword" type="password">
</form>

// import 
import { FormBuilder, FormGroup, Validators } from "@angular/forms";

export class AuthorizationFormComponent {

  public loginForm : FormGroup;

  @ViewChild('userLoginInput') userLoginInput;

  constructor(
    private _builder : FormBuilder,
  ) {
    // Form builder and validation configuration
    this.loginForm = this._builder.group({
      userLogin: [ '', [ Validators.required ] ],
      userPassword: [ '', [ Validators.required ] ],
    });
  }

  onSubmitLoginForm () {
    this.userLoginInput.nativeElement.focus()
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question