* ngTo reset all form values ​​when adding a new input element

I have an Angular2 application with a button that can add another loan to my loans. My * ngFor is also pretty simple:

    <div *ngFor="let loan of myLoans">
      <label>{{loan.name}}</label>
      <input type="text" name="loan.name" [(ngModel)]="loan.amount">
    </div>

myLoansis an array of Loan objects with nameand parameters amount. My button is also very simple.

<button id="addLoan" type="button" (click)="addLoan()">Legg til lån</button>

AddLoan () function:

addLoan(): void{
    var newLoan = new Loan();
    this.myLoans.push(newLoan);
}

My problem is that when I add a new loan to the list, any value that I had in the input field for my other loans returns to 0 or any value that I set in the constructor for the loan object.

Downloading the application shows this picture.

What now

ngModel works when dialing a number

enter image description here

After pressing the “Legg til lån” button, the value of the first input is reset

enter image description here

ngModel is still working for the first input if I try to enter a different number

enter image description here

- , ?

+11
5

AJT_82 , , , , , , html

<div *ngFor="let loan of myLoans">
  <label>{{loan.name}}</label>
  <input type="text" [name]="loan.name" [(ngModel)]="loan.amount">
</div>

[]. , , , .

Update: , , .

<div *ngFor="let loan of myLoans; let i=index">
  <label>{{loan.name}}</label>
  <input type="text" [name]="loan.name + '_' + i" [(ngModel)]="loan.amount">
</div>
+20

99% , name, ngModel.

name . Angular ngModel , name.

, name, : name="loan.name" loan.name , .

, loan, , , .

, name, :

<div *ngFor="let loan of myLoans; let i=index">
  <label>{{loan.name}}</label>
  <input type="text" name="loan.name{{i}}" [(ngModel)]="loan.amount">
</div>
+5

, [(ngModel)] * ngFor. myLoans, ngModel ( )

:

myLoans = [0, 1, 2, 3]

, [[ngModel]) (3).

125 ,

myLoans = [0, 1, 2, 125]

, Angular

myLoans = [0, 1, 2, 125, 0]

Input.value now = 0


: ngModel * ngFor, , (click) Angular Selector. :

<input #loan ..>
<button (click)="addLoan(loan.value)">Add Loan</button>
+1

, . , . ng2 typescript . tsconfig:

{
  "compilerOptions": {
    "target": "es5",
    "typeRoots": ["node_modules/@types/"],
    "types": [
      "node",
      "es6-shim"
    ]
  }
}

"var" . "let", . , var. , .

+1

@Joo_Beck [name]=loan.name name='loan.name'. . {{i}} , , .

<div *ngFor="let loan of myLoans; let i=index">
  <label>{{loan.name}}</label>
  <input type="text" name="loan.name{{i}}" [(ngModel)]="loan.amount">
</div>

, , @AJT_82.

@Cassiano, !

+1

Source: https://habr.com/ru/post/1675834/


All Articles