Background Info
I need to modify an existing drop down component that is populated from a database, to add an "All locations" option. We do not want to add this to the db, but just include in the list of options - as the first item.
I am not an angular developer and so I'm a little lost on how to accomplish this:
Code
From what I can tell, the drop down is created from logic inside a location-options.component.ts file:
@Component({
selector: 'app-location-options',
template: `
<form [formGroup]="parentForm">
<ptrn-field label="{{ title }}" emptyLabel="None specified" >
<select
#options
(change)="setValueChanged(options.value)"
formControlName="locationSelected"
>
<option
*ngFor="let location of locationOptions"
[value]="location.locationCode"
[id]="location.id"
[selected]="optionSelected === location.locationCode"
>
{{ location.locationCode }}
</option>
</select>
<ptrn-field-error name="required">Please enter a description.</ptrn-field-error>
</ptrn-field>
</form>
`,
styles: [],
changeDetection: ChangeDetectionStrategy.OnPush,
})
Can someone point me in the right direction?
CodePudding user response:
Several ways you can do it.
Simple solution would be :
Write an option tag wth default value just before the option tag doing ngFor.
<select
#options
(change)="setValueChanged(options.value)"
formControlName="locationSelected"
>
<option value="">
All locations
</option>
<option
*ngFor="let location of locationOptions"
[value]="location.locationCode"
[id]="location.id"
[selected]="optionSelected === location.locationCode"
>
{{ location.locationCode }}
</option>
</select>
Then there are crazy ways like add an rxjs pipe to modify api response to add default option or you can create a custom pipe that modifies locationOptions.
It's up to you.