Reputation: 525
Question:
How can I display a pre selected item from my dropdown just based on it's ID.
Explanation/Problem:
My dropdown options are from a dynamic web service that finds me Providers based on a users ZipCode. An example of a Provider is {Phone: "5093240817", sp_id: "1", Name: "John Doe" … }... The dropdown displays the name for the user to pick but we only store the ID. So the Problem that I am facing is if the user returns to change their provider, I want to display the users original Providers Name, but I only have the ID.
Sidenote: we can't store the value of Name because the web service can change the providers name value.
My Attempt:
My idea to solve this was to "filter" the array of Providers based on the original ID and then find the name that way. I'm new to Angular and typescript so i'm having trouble...
My idea.
I was reading another SO post and trying to understand how they do this, but again i'm just having trouble. (How do I filter an array with TypeScript in Angular 2?)
const showValue = this.serviceProvider.filter(sp_id =>
this.selectedAppointment.sp_id)
**this.selectedAppointment.sp_id hold the original ID value.
Service Providers Options
{Phone: "5093240817", sp_id: "1", Longitude: -77.3841197, Provider Type: "Pediatric", Latitude: 38.9808589,Name: "John Doe" …}
1
{Phone: "097420454", sp_id: "3", Longitude: -77.3898602, Provider Type: "Pediatric", Latitude: 38.914697200000006, Name: "Kim" …}
2
Upvotes: 0
Views: 318
Reputation: 525
Ended up solving this issue by iterating through the options and then setting the matching value in the form!
setProvider(sp_id) {
for(let sp in this.serviceProvider) {
if (sp_id == this.serviceProvider[sp].sp_id) {
(<FormGroup>this.patientAppointmentForm)
.patchValue({serviceProvider:
this.serviceProvider[sp].sp_id}, {onlySelf: true});
}
}
}
Upvotes: 0
Reputation: 16675
In your example sp_id
is the service provider option being passed to each iteration of the filter
callback. I think you may be misunderstanding how Arrow functions work: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Also, look at the filter
method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
I think what you want to do is this (which would compare the sp_id
of the option to the selected value):
this.serviceProvider.filter(sp => sp.sp_id === this.selectedAppointment.sp_id);
Or, to provide some clarity:
this.serviceProvider.filter((serviceProvider) => {
return serviceProvider.sp_id === this.selectedAppointment.sp_id;
}
Upvotes: 1