1

I have this input field:

<input
  class="form-control"
  [(ngModel)]="event.name"
  name="name"
  required>

And this validation check:

public isEventValid(Event: Event): boolean {
    if (Event.name.length == 0) {
        this.msgs = [{severity: 'error', summary: '', detail: 'Er is geen Eventnaam ingevuld'}];
        return false;
    }
    if (Event.name.trim().length == 0) {
        this.msgs = [{severity: 'error', summary: '', detail: 'De naam mag niet alleen uit spaties bestaan'}];
        return false;
    }
    if (Event.languageId == 0) {
        this.msgs = [{severity: 'error', summary: '', detail: 'Er dient een taal te worden gekozen'}];
        return false;
    }
    return true;
}

How can I set the cursor on the input field when one of the if statements is false in the validation check?

Peter Boomsma
  • 8,851
  • 16
  • 93
  • 185
  • I hope the linked answer is close enough. Otherwise post a comment about what is unclear. – Günter Zöchbauer Sep 04 '17 at 09:04
  • I've checked that, but that example doesn't set the input to a ng-model. – Peter Boomsma Sep 04 '17 at 09:11
  • I don't know what you mean by "set the input to a `ng-model`. Setting the focus is the same whether you use `ngModel` or not. – Günter Zöchbauer Sep 04 '17 at 09:13
  • When the validation fails I want to to set the cursor in a selected input field. Such as "name". I want to do that using the ngModel attribute. With the example you have shared it uses ` this.elementRef.nativeElement, 'focus', []);` to set the focus. So it's not targeting an already defined element. – Peter Boomsma Sep 04 '17 at 09:17
  • As I said `ngModel` won't help you in setting the focus. – Günter Zöchbauer Sep 04 '17 at 09:19
  • Here are other answers that might help https://stackoverflow.com/questions/45073216/how-to-set-focus-on-specific-input/45073505#45073505, https://stackoverflow.com/questions/40886012/how-to-navigate-focus-to-the-next-item-in-angular2/40886144#40886144, https://stackoverflow.com/questions/36329658/angular-2-select-object-from-the-dom-and-set-the-focus/36329983#36329983 – Günter Zöchbauer Sep 04 '17 at 09:20
  • So it's not possible to use ngModel to do this? That's weird. I would have thought that would be a great way to do this. – Peter Boomsma Sep 04 '17 at 09:23
  • Angular doesn't provide anything to set the focus, except accessing the DOM yourself and calling `focus()` on an element. `ngModel` also doesn't allow you to access the element. `ngModel` only cares about the value. – Günter Zöchbauer Sep 04 '17 at 09:27

0 Answers0