menu

Questions & Answers

Angular not serializing all form elements

When I try to submit an Angular form one specific input does not get serialized into the NgForm object along with all the others. However, I can't see what is unique about this input. To make matters worse, this form is used in both creation and updating of the entity, and the serialization problem only occurs during creation. If at all relevant, this is all happening inside of an Angular dialog. The problematic input is "manufacturer".

My question is: has anyone seen this before??

I don't expect the code to be helpful, but here it is:

HTML:

<form action="#" #OrderItem="ngForm">
  <mat-form-field>
    <mat-label>Manufacturer</mat-label>
    <input matInput name="manufacturer" [(ngModel)]="manufacturer">
  </mat-form-field>
  <mat-form-field>
    <mat-label>Model/Brand</mat-label>
    <input matInput name="modelOrBrand" [(ngModel)]="modelOrBrand">
  </mat-form-field>
</form>
<button mat-button (click)="submit(OrderItem)">
  <span>{{ data.edit ? "Update" : "Add to Cart" }}</span>
</button>

Component:

export class MoreInfoDialogComponent implements OnInit {
  manufacturer: string;
  modelOrBrand: string;

  submit(item:NgForm): void {
    console.log(this.manufacturer); // displays the expected value
    console.log(item.value); // displays an object with modelOrBrand correctly populated, but no manufacturer key
  }

}
Comments:
2023-01-25 09:42:06
It would help if you could include a minimal reproducible example, prefferably in an online editor like Stackblitz. From the code you posted, I can't tell what could be wrong with it.
2023-01-25 09:42:06
If you rely on form groups instead of simple controls, why not use reactive forms instead ?
Answers(0) :