javascript - Angular 4 array of ngModels - how to handle the name attribute -


here's class:

interface ihobby {   name: string;   type: string; }  class user {   constructor(public name: string, public hobbies: ihobby[]) { } } 

now i'm trying template form in angular 4. i've noticed in order display hobbies, need iterate through them. so, here's html:

<div *ngfor="let h of user.hobbies; let = index">     #{{i}}<br />   <input [(ngmodel)]="h.name" name="hobby_name[{{i}}]" /> <br /><br />   <input [(ngmodel)]="h.type" name="type[{{i}}]" />     <br /><br />   <button class="btn btn-warn" (click)="remove(i)">remove</button>     <br /><br /> </div> 

while works, i'm not quite sure if:

  1. i'm doing correct angular 4 way - should use ngmodel each item in array?

  2. is ok define names name="hobby_name[{{i}}]"? because name="hobby_name_{{i}}" works well. correct, html5 , angular 4 way?

here's working sample: https://plnkr.co/edit/chosfhbthd3da9ffqnpx?p=preview

you don't need use name attribute since you're binding inputs directly model. if want see instant changes in model, can keep using [(ngmodel)], if want update model on form submit only, should not use ngmodel. reactive form this:

<div [formgroup]="form">     <div formarrayname="hobbiesformarray">         <div *ngfor="let h of user.hobbies; let = index" [formgroupname]="i">             #{{i}}<br />           <input formcontrolname="name" /> <br /><br />           <input formcontrolname="type" />             <br /><br />           <button class="btn btn-warn" (click)="remove(i)">remove</button>             <br /><br />         </div>     </div> </div> 

and in component like:

form: formgroup;  constructor(fb: formbuilder) { this.form = this.fb.group({       name: '',       hobbies: this.fb.array([])     }); }  ngonchanges() {     this.form.reset({       name: this.user.name     });     this.sethobbies(this.user.hobbies); }  hobbiesformarray(): formarray {     return this.form.get('hobbiesformarray') formarray; };  sethobbies(hobbies: ihobby[]) {     const hobbiesformarray = this.fb.array(hobbies.map(hobby => this.fb.group(hobby)));     this.form.setcontrol('hobbiesformarray', this.fb.array()); } 

then in onsubmit method convert form model user object:

const formmodel = this.form.value;  const newhobbies: ihobby[] = formmodel.hobbiesformarray                         .map(() => (hobby: ihobby) => object.assign({}, hobby))  const newuser: user = {   name: formmodel.name string,   hobbies: newhobbies }; 

and save newuser object whatever means have.


Comments