0

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 ?

3
  • how are you setting default value? Commented Sep 10, 2018 at 12:44
  • No, I am just posting the value from database into the input, then trying to read it using script above. Commented Sep 10, 2018 at 12:45
  • No default values are set Commented Sep 10, 2018 at 12:46

2 Answers 2

3

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]);
Sign up to request clarification or add additional context in comments.

1 Comment

That's it. Thanks. And how to set a predefined value of mat-select options ?
1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.