how come all the input boxes are binded after I try to add user?
https://stackblitz.com/edit/angular-4e65ne
I am assigning them to different elements in the array.
You are adding the same user object to your array multiple times. Also unnecessarily complicated, you can reduce it to this:
You can reduce your AppComponent
to
import { Component } from '@angular/core';
import { NewUser } from './user.model';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
public user1 = Array<NewUser>();
addUser() {
this.user1.push(<NewUser>{
userId: 'userId1',
reason: 'reason1'
});
}
}
Then your binding works just fine:
<div class="input-group-prepend">
<span class="input-group-text addUser" (click)="addUser()">+ User</span>
</div>
<div *ngFor="let i of user1; let index = index">
<div class="input-group mb-3" >
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">User Id</span>
</div>
<input type="text" class="form-control" name="userid-{{index}}" [(ngModel)]="user1[index].userId"> {{index}}
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">Reason</span>
</div>
<input type="text" class="form-control" name="reason-{{index}}" [(ngModel)]="user1[index].reason">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1" (click)="removeUserId(index)"><i class="fa fa-trash" aria-hidden="true"></i></span>
</div>
</div>
</div>
Stackblitz: https://stackblitz.com/edit/angular-bamrwa?file=src%2Fapp%2Fapp.component.ts
Well, you are assigning the same NewUser object at every position on your array. You have to initialize your variable this.user with an empty object at the end of your method:
addUser(){
_.assign(this.user[this.userCount], <NewUser>{
userId: 'userId1',
reason: 'reason1'
});
this.user1[this.userCount] = this.user;
this.userCount++;
this.user = <NewUser>{}; // Here you have to reset the variable
}
You can simply add the new object to array
:
addUser(){
this.user1.push({userId:'', reason:''});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.