4

I am working on an Angular 2 project, where I am using forms and validation and have come to the following problem. I have a page with 3 fields:

  • height
  • weight
  • BMI

I would like ALL 3 fields to be in my form so I have done the following:

<input name="height" type="text" class="form-control" formControlName="height">
<input name="weight" type="text" class="form-control" formControlName="weight">
<input name="bmi" type="text" class="form-control" formControlName="bmi">

So far this works fine. Although, I want BMI calculated automatically. I have a function detecting changes on the two fields (height and weight) and calculates the BMI and outputs it in the BMI input field. This works as intended as well.

HOWEVER, I would like to disable the BMI input field in order to prevent the user from being able to type anything. So I have the 3 following criteria:

  • The input field here meant to serve as a read only field for the user.
  • I also want the BMI to be part of formgroup which I send to my database when all 3 fields are valid.
  • (optional, but very much wanted) I want the BMI field to be an input field with the result from height and weight as I have implemented it, not as plain text.

I have tried putting a [disabled]=true tag on the BMI input field which doesn't work and gives me a warning that I should add the disabled tag in the formgroup. When I do this or use this command: this.myForm.controls['BMI'].disable(); it DOES disable it as intended, but also removes it from the formgroup. This means when I submit my formgroup only the value of height and weight is sent, bmi is left out.

How can I do this? Any help is greatly appreciated!

Sina Sohi
  • 2,719
  • 9
  • 33
  • 50

3 Answers3

1

Have you tried placing a readonly attribute on the input?

<input name="bmi" type="text" class="form-control" formControlName="bmi" readonly>
Jonathan Walton
  • 449
  • 3
  • 18
0

Are you using some kind of UI framework at all? http://semantic-ui.com/collections/form.html#read-only-field

itmitica
  • 501
  • 3
  • 10
0

formGroup.getRawValue() will return even the disabled fields,

Source

juansb827
  • 150
  • 2
  • 7