2

I need to use input field witch unique name for all fields. I cant't use [ngModelOptions]="{standalone: true}", because I have validation problem in the form (these fields are ignored in validation). This is part of my code:

<ng-template pTemplate="rowgroupfooter" let-vehicle>
    <td>
      <mat-input-container class="full-width" color="warn">
        <input matInput [(ngModel)]="vehicle.subscription_price" [ngModelOptions]="{standalone: true}" required [disabled]="viewMode" type="number" min="0" [ngClass]="{ 'edited-price': vehicle.isSubscriptionPriceChanged }"
          (input)="vehicle.isSubscriptionPriceChanged=true;" pInputText appendTo="body" style="background-color: white">
        <mat-error>To pole jest wymagane</mat-error>
      </mat-input-container>
    </td>
...(more rows)
</ng-template>

So, how to add name="index" dynamically.

E.g

name='1'

name = '2'

...

name = 'n'

1
  • Have a look at Angulars reactive forms. There is a FormArray which is what you need. Commented Aug 21, 2018 at 10:32

2 Answers 2

1

If your intention is to use multiple inputs in form you can use form array here:

reactive form array

Basic Demo

Create controls:

constructor(private fb: FormBuilder) {}

 createForm() {
    this.myForm = this.fb.group({
      people: this.fb.array([this.createArray()])
    })
  }

  createArray() {
    return this.fb.group({
      name: null,
      addresses: null
    });
  }

Access Controls:

{{myForm.controls.people.controls[i].controls.name.value}}
Sign up to request clarification or add additional context in comments.

Comments

0

I suggest to use Reactive Forms, so you can benefit of FormArray:

https://angular.io/guide/reactive-forms#dynamic-controls-using-form-arrays

so you can easily do things like:

<div formArrayName="yourFormArray">

  <div *ngFor="let control of yourFormArray.controls; let i=index">
    <!-- The repeated template -->
    <label>
      Your Control:
      <input type="text" [formControlName]="i">
    </label>
  </div>
</div>

2 Comments

so I guess in your Component's Class you will retrieve somehow the data from the server and according to that, you generate the controls of the FormArray
I should better specify my question, because client can add in any time new row with inputs, so I don't know how many rows i will have. (It was mistake before)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.