Mateusz Duda
Mateusz Duda

Reputation: 59

Angular - How to call object property from collection in Form input

Please help, I have collection in angular component:

 collection: collectionAbs[];
    
 export interface collectionAbs{
   name: string;
   prop: string;
   secondProp: number;
 }

And I initialize:

    this.collection.forEach((item ,index) => {
      formGroup.addControl(index.toString() + "-prop", new FormControl('', [Validators.required])),
      formGroup.addControl(index.toString() + "-secondProp", new FormControl('', [Validators.required]))
    });

Object is initiated and I want to update properties in form. I have something like this:

  <div *ngFor="let item of collection; let i = index" >
         <input type="text" name="collection[{{i}}].prop">
         <input type="number" name="collection[{{i}}].secondProp">
  </div>

But I haven't no idea how to assign now this values to my objects collection. Maybe someone have better solution for this problem?

@Edit

FormGroup:

 var formGroup: FormGroup;

 formGroup = new FormBuilder().group({
   anotherFormInputOne: new FormControl(null, [Validators.required]),
   anotherFormInputTwo: new FormControl(null, [Validators.required])
 });

Thanks!

Upvotes: 0

Views: 455

Answers (1)

Chris
Chris

Reputation: 71

it should just be a case on submit of the form of doing:

    this.collection.forEach((item ,index) => {
      item.prop = formGroup.controls[index.toString() + "-prop"].value;
      item.secondProp = formGroup.controls[index.toString() + "-secondProp"].value;
    });

Upvotes: 1

Related Questions