Changing the value of a hidden field in a reactive form in Angular

Viewed 6158

I have a reactive form that has the same (two) input text fields for several different scenarios. When a user selects a scenario option from a list, the form is shown and a hidden field within that form is updated with a keyword for the selected scenario, e.g.

<input formControlName="action" type="hidden" value="{{theaction}}">

My problem is that while that field is being updated (i.e. I can see it in reveal codes), the value doesn't seem to be bound to the form when it's submitted (i.e. the field is empty on arrival at the server).

What bit about reactive forms am I missing here?

Thanks/Tom

1 Answers

I recently had a need to include information on a reactive form (e.g. an id), some property of my data model that should not be exposed on the UI. I created a FormControl for the property, which allowed me to store and manipulate the value, but I did not create a corresponding <input> in the template. Worked like a charm. E.g.

profileForm = this.fb.group({
  id: [null],                              //hidden field
  firstName: ['', Validators.required],
  lastName: ['']
});

in the template

<form [formGroup]="profileForm">

  First Name: <input type="text" formControlName="firstName" />

  Last Name:  <input type="text" formControlName="lastName" />

  [...]

</form>
Related