How to focus input field created dynamically using an Angular model driven form

1.1k views Asked by At

I'm using model driven forms in an Angular 7 application, and one of them allows the user to add/delete a group of fields dynamically. Here's a visual reference of what I mean:

enter image description here

This is the FormModel I use:

this.formModel = new FormGroup( {
    id : new FormControl(''),   
    name : new FormControl('', Validators.required), 
    comment : new FormControl(''),
    options : new FormControl(3), 
    domain_users: new FormArray([this.createDomainUser()])
    });

The dynamic property is domain_users, which is a FormArray of FormGroup with 3 FormControl (domain, username and password). When the user clicks the add button, this is what I do:

let du = this.formModel.get('domain_users') as FormArray;

if(nodes) {
  nodes.push(this.createDomainUser());
}

I'd like that, when the user clicks the add button, the focus moves to the 'domain' field of the newly created row. What would be a good 'Angular way' of doing this?

Thanks in advance,

1

There are 1 answers

0
Fel On

This is the solution I found:

In the HTML template:

<div class="ui-grid-row"
   *ngFor="let node of getDomainUsers().controls; let i = index" 
   [formGroupName]="i"
   #nodeInput>

In the component source:

@ViewChildren('nodeInput') nodeInputs: QueryList<ElementRef>;

[...]
nodeAdd() {
  [...]

  try {
    // Try to get the first input element of the last row added
    let lastInput: HTMLInputElement = this.nodeInputs.last.nativeElement.children[0].children[0];

    lastInput.focus();
  }
  catch(e) {
    // Couldn't access the input element
  }  
}