2

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,

Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83
Fel
  • 4,428
  • 9
  • 43
  • 94
  • 2
    This should be helpful https://stackoverflow.com/questions/41190075/how-do-i-programmatically-set-focus-to-dynamically-created-formcontrol-in-angula?rq=1 – Amit Chigadani Nov 12 '18 at 13:14
  • Thanks, your answer pointed me to the solution. Cheers! – Fel Nov 12 '18 at 14:32

1 Answers1

0

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
  }  
}
Fel
  • 4,428
  • 9
  • 43
  • 94