Sunday 27 December 2020

Focus in angular formArray (after adding a new row)

The Template logic Looks like this:  

<div formArrayName="inputs" class="col-md-6 col-12" 

     *ngFor="let inputCtrl of form.get('phones').controls; 
             let i=index; trackBy:trackByFn">
     <div [formGroupName]="i">
        <input #input type="text" class="phone" 
             (blur)="addRecord()"
             formControlName="input" />
     </div>
 </div>

import { AfterViewInit, QueryList, ViewChildren, OnDestroy } from '@angular/core';
 import { Subscription } from 'rxjs/Subscription';

 // .. other imports

 export class MyComp implements AfterViewInit, OnDestroy {
   @ViewChildren('input') rows: QueryList<any>;
   private sub1:Subscription = new Subscription();
   //other variables ..

 // changes to rows only happen after this lifecycle event so you need
 // to subscribe to the changes made in rows.  
 // This subscription is to avoid memory leaks
 ngAfterViewInit() {
   this.sub1 = this.rows.changes.subscribe(resp => {
     if (this.rows.length > 1){
       this.rows.last.nativeElement.focus();
     }
   });
  }

  //memory leak avoidance
  ngOnDestroy(){
    this.sub1.unsubscribe();
  }


   //add a new input to the page
   addInput() {
     const formArray = this.form.get('inputs') as FormArray;

     formArray.push(
        new FormGroup(
        {input: new FormControl(null, [Validators.required])}
     ));
    return true;
   }

 // need for dynamic adds of elements to re 
 //focus may not be needed by others
 trackByFn(index:any, item:any){
    return index;
 }

No comments:

Post a Comment

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...