Reputation: 4972
I am getting a value from PHP server to angular 6 through HttpClient, and this value is sent to a formControlInput
to be set as a default value:
<mat-form-field color="warn">
<input matInput formControlName="unit_type"
placeholder="Unit type" value="{{unit_type}}">
</mat-form-field>
I am saving the same value into a variable, to compare it to the value of the input so I can detect a change, to know whether I activate the update button or not:
this.unit_type = data['unit_info'][0]['unit_type'];
Consoling this variable is showing properly, and the value is displayed inside the input.
Now when I get the value of it again like the following:
unit_type_upd = this.formGroup.controls['unit_type'].value;
console.log(unit_type_upd);
It shows me empty value, but when I change it, it will detect the change, and make the comparing process.
Why unit_type_upd
is not getting the value displayed inside the input on component load ?
Upvotes: 0
Views: 4506
Reputation: 5709
When you use Angular Reactive Form
you shouldn't bind data to properties like
value="{{unit_type}}"
The correct way is this in your component
this.formGroup.controls['unit_type'].setValue(this.unit_type)
You can set default value when you create your FormControl
like this
new FormControl('default value', [Validators.required]);
Upvotes: 3
Reputation:
value
attributes shouldn't be used in Angular : they're very confusing.
In your case, you indeed set a default value : but you set only the value of the HTML input itslef, no the one of Angular !
To fix the default value, you must do it a form group creation :
this.formGroup = this.formBuilder.group({
unit_type: 'default value here'
});
If you want to store the first value of your form, store it once your form has been created :
this.defaultValue = this.formGroup.value;
You can now use the reset method to reset it :
this.formGroup.reset(this.defaultValue);
And if you want to check if the value has changed, you don't need to compare two values ; simply check the form status ! (either dirty
or touched
, see what suits you best)
Here is your HTML :
<mat-form-field color="warn">
<input matInput formControlName="unit_type" placeholder="Unit type">
</mat-form-field>
Upvotes: 1