Home > database >  why does ngModel focus disappear after every letter written
why does ngModel focus disappear after every letter written

Time:07-11

html
it's line segment my component html

<div *ngFor="let phoneAddress of contact.adress; let i = index">
    <label for="adress">Adress</label>
    {{phoneAddress}}
    <input type="text" [(ngModel)]="contact.adress[i]" [ngModelOptions]="{standalone: true}">
    <button (click)="removeAddress(i)">-</button>
    <button (click)="addAddress()"> </button>
</div>

ts it's line segment my component ts

addAddress() {
  this.contact.adress.push("");
  console.log(this.contact.adress);
}

removeAddress(ind: number): void {
  this.contact.adress.splice(ind, 1);
}

I don't understand what I'm doing wrong

CodePudding user response:

I am giving you a sample code that you could use here, I'd advise to use a form to make it easier: https://stackblitz.com/edit/angular-form-group-form-array-dynamic?file=src/app/app.component.html

The problem with the current implementation is that everytime you enter a key, the entry gets changed, the part is re-rendered ( your input )

How could you solve this though ?

You could use a trackByFunction

<div *ngFor="let phoneAddress of contact.adress; let i = index; trackBy: trackByMethod">
  <label for="adress">Adress</label>
  {{ phoneAddress }}
  <input
    type="text"
    [(ngModel)]="contact.adress[i]"
  />
</div>
trackByMethod(index: number, el: any): number {
   return index;
}

This make sure the whole div isn't re-rendered everytime

CodePudding user response:

As Ziyed say the problem is that you're iterating over the same array you're change. The correct response is use trackBy, but another way is create an array "on fly"

<div *ngFor="let phoneAddress of 
      '.'.repeat(contact.adress.length).split(''); 
      let i = index">
   <label for="adress">Adress</label>
   {{contact.adress[i]}}
   <input type="text" [(ngModel)]="contact.adress[i]">
</div>

NOTE: Not use [ngModelOptions]="{standalone: true}". This is only when you're mannaging a Reactive Forms and include an input with [(NgModel)] that it's not related with the FormGroup

  • Related