Issue
I have a reactive form in my component.when component initializing I want to set the value to the select field in my component, not as an option.value is getting from the server as observable after subscribing to it I want to display that values in the select field as default value
I tried
this.formName.get('controlName').setValue('valueFromServer')
and
this.formName.get('controlName').patchValue('valueFromServer')
and couple of stackoverflow solution as well but those are not worked for me.this is my stackblitz example.can any one tell me whats wrong here
https://stackblitz.com/edit/angular-izarqy
Solution
You are setting the value to form control in right way as of my knowledge.
However as @Adrita pointed out dropdown will select the value if Options value attribute contains it otherwise selection won't happen.
have look at this StackBlitz.
In Template :
this.tourPageForm.get('accomadation').setValue('valueFromServer'),
In View:
<select style="width:100px" formControlName="accomadation" class="form-control border">
<option value="valueFromServer">1</option>
</select>
Edit :
Actually setValue and patchValue are seems working here. We check that with below approach..
this.tourPageForm.get('accomadation').setValue('valueFromServer');
this.tourPageForm.get('mealType').setValue('Value recive from Server');
console.log(this.tourPageForm.value)
When we try to console tourPageForm, will be able to observe below values..
accomadation: "valueFromServer"
mealType: "Value recive from Server"
transportation: ""
Which means setValue and patchValue are working fine but form dropdown is not able to select given value because they are not part current dropdown Options.
Answered By - Ganesh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.