I am using angular 6
My html is
<form [formGroup]="myForm" >
<label>
<input type="text" formControlName="name" placeholder="name" required autofocus >
</label>
<label>
<select name="drop" formControlName="drop">
<option value="developer"selected >developer</option>
<option value="designer">designer</option>
<option value="admin">admin</option>
</select>
</label>
</form>
Even though I set selected
in the "developer" option
when the page first loads, the "developer" is not selected. I guess that this is a small bug of angular that cannot render the html right, so I put in my component, as I define the form :
myForm = this.formBuilder.group({
name:['',Validators.required],
drop:['developer']
});
and it works.
What is really weird is that when I do this.myForm.reset();
inside another button, placed outside the form, the "name" is empty as it should be, but the dropdown is also completely empty, just blank, but it should show "developer", right?
That button hides some elements and should reset the form, it is outside the form and it does
getOtherData(id){
this.myForm.reset();
This does not work, so I have to do
this.myForm.setValue({
name: '',
drop: 'developer'
});
in order to actually reset the form. What is going wrong with the select
combined with the reset
? I want to use reset
once and completely reset the form, without "hacks" How can I do that?
Thank you
What is really weird is that when I do
this.myForm.reset()
; inside another button, placed outside the form, the"name"
is empty as it should be, but the dropdown is also completely empty, just blank, but it should show"developer"
, right?
No it shouldn't. What happens when we call reset()
? Most importantly it sets all your values to null
.
In your select, the field you want selected has the value "developer"
, so this will of course not then be set, as you have just reset the value to null
, i.e
null === 'developer' // false!
This is an Angular form, so Angular really doesn't care about the HTML attributes (in this case selected
), but listens to the form controls and what are going on there. So what you need to do, is to reset the form with the value you want, for that you can give the value on reset
:
this.myForm.reset({
name: '',
drop: 'developer'
});
You should use patch method to reset Form
setValue() methods to update all FormControl values.
patchValue() method will also set Formcontrol values from a model but only for those which we have mentioned in the model.
this.myForm.patchValue({
name: ''
});
If you want to use reset method for specific FormControl values
this.myForm.get('name').reset();
Example: https://stackblitz.com/edit/patch-with-form
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With