0

I have an array like below

standardInput:any = [{val:'1'},{val:'2'},{val:'3'}];

When i loop it in my view

<div class="form-group row text-right" *ngFor='let row of standardInput' >{{row.val}}
     <label class="col-sm-3 form-control-label m-t-5" for="password-h-f"></label>
         <div class="col-sm-9 form-control-label m-t-5" for="password-h-f">
           <div class="row">
              <div class="col-sm-9" >
                  <input class="form-control" name="roles" [formControl]="form.controls['service_standard_sub_heading']" [(ngModel)]="row.val" id="email-h-t" type="email">
               </div>
              <div class="col-sm-3">
                <button class="btn btn-danger" (click)="removeInputs('standard',i)">Remove</button>
               </div>
           </div>
          </div>
       </div>

The output is :3 3 3,it is showing only the last object in the array for the 3 iterations.I am not able to understand what's the reason.Can anyone please suggest help.Thanks.

0

1 Answer 1

1

I believe you are using template-driven form, if not, let me know and we can look at a solution for model-driven form :)

In forms, the name attribute needs to be unique. Even though the ngModel is unique, Angular doesn't really care about it, but looks at the name attribute instead. Since you are using a template-driven form and ngModel, I see no need to use formControl here, you can just rely on the the ngModel and name attribute instead. So, to get the unique name attribute, we can bind the row.val to it, like so:

[name]="row.val"

So your complete template would look like this:

<form #form="ngForm">
  <div class="form-group row text-right" *ngFor='let row of standardInput'>
    <input class="form-control" [name]="row.val" [(ngModel)]="row.val">
  </div>
</form>
Sign up to request clarification or add additional context in comments.

1 Comment

How did it go with this code? Was template driven form the correct way? :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.