Reputation: 474
I'm doing an app with Ionic framework, so far I have inputs generated by *ngFor and I want to get the value of each input after clicking on a button. I've tried with Reactive forms but was not able to make it work.
<ion-list>
<ion-item *ngFor="let item of players; index as i">
<ion-chip>
<ion-input placeholder="Nombre jugador {{i+1}}" type="text"></ion-input>
<ion-icon name="person-add"></ion-icon>
</ion-chip>
</ion-item>
<br />
</ion-list>
and my .ts file.
ngOnInit() {
this.getJugadores();
}
getJugadores(){
this.storage.get("num_players").then(x =>{
if (x){
this.players = new Array(x);
}else{
console.log("error");
}
});
}
I want to store each value in an array of objects.
Upvotes: 2
Views: 615
Reputation: 60528
With Angular, one of the easiest ways to get/set data onto a form is to simply use [(ngModel)]
data binding.
1) Define a structure for your data. If you have multiple inputs, consider defining an array.
2) Bind to that structure using [(ngModel)]
.
Here is some information that may help: https://angular.io/guide/template-syntax#binding-syntax-an-overview
Template code
<div *ngFor="let item of players; index as i">
<input placeholder="Nombre jugador {{i+1}}" type="text"
[(ngModel)]="item.name"/>
</div>
Component code
players: Player[] = [];
ngOnInit() {
// Call a service to get data
// Hardcoded here as an example
this.players = [
{id: 1, name: "Joe"},
{id:2, name: "Stefan"}
]
}
Interface code
export interface Player {
id: number,
name: string
}
I have a working example here: https://stackblitz.com/edit/angular-b5uppm
Upvotes: 3