I got a modal form inside a loop with menus.
<div *ngFor="let menu of menus let i = index">
...
<form #updateMenu="ngForm" [formGroup]="nameForm" (ngSubmit)="onSubmit(updateMenu)" style=" padding: 20px; display:flex; justify-content:center; flex-direction: column;" enctype="multipart/form-data">
<mat-form-field appearance="fill">
<mat-label>Title</mat-label>
<input matInput placeholder="{{menu.title}}" formControlName="title" [(ngModel)]="menu.title" required>
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>Description</mat-label>
<textarea matInput name="description" formControlName="description" placeholder="example: All of our pizzas are amazing" required></textarea>
</mat-form-field>
<br>
<label>Image of menu *</label>
<img src="{{url + 'menu/get-image/' + menu.image}}" style="height:150x;" />
<input type="file" name="image" (change)="onSelectedFile($event)" required/>
<br>
<input type="submit" class="submit" value="SEND"
[disabled]="!updateMenu.form.valid" style="border:none; background:#181818; height: 40px; color: #f1f1f1; font-size: 22px;" />
</form>
</div>
I have a problem with formControlName and it is that when using [(ngModel)] it always loads the values of the last element of the for loop
I have tried to make it like formControlName to make it dynamic but I get an error:
TS2339: Property 'title' does not exist on type 'MenuupdateComponent'
My component with formBuilder:
public nameForm:FormGroup;
constructor(private _AdminmenuService:AdminmenuService, private formBuilder: FormBuilder) {
this.nameForm = this.formBuilder.group({
title: '',
description: '',
image: ''
});
}
How can I fix that? Thank you so much!
There are two available solutions:
Do not merge reactive form with template driven form
use form array to build iterated form