Upon signing up for my Angular application, users are required to set up their accounts by adding instruments to their profile.
An instrument is defined by the following interface:
export interface Instrument {
id: string;
name: string;
groupId: string;
}
The concept involves having a list of dropdown menus, initially starting with just one dropdown. Below each dropdown, there is a button that, when clicked, adds an empty dropdown field. I have successfully implemented this functionality in my code. However, I encountered an issue where selecting an instrument in the first dropdown and then adding another dropdown results in the option in the first dropdown being reset, giving the appearance that nothing is selected (even though the array remains unchanged except for the new empty value).
Here is the code snippet:
HTML
<div
*ngFor="let userInstrument of userInstruments; let id = index"
>
<mat-form-field appearance="fill" fxFlex>
<mat-label>Instrument</mat-label>
<mat-select placeholder="Guitar" [(ngModel)]="userInstruments[id]" name="item">
<mat-option value="">
None
</mat-option>
<mat-option [value]="instrument.id" *ngFor="let instrument of instruments">
{{instrument.name}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
<p id="add-instrument" (click)="addInstrument()">
Add another instrument?
</p>
Typescript
userInstruments: string[] = [];
instruments: Instrument[] = [];
constructor(private utilsDataService: UtilsDataService) {
this.utilsDataService.loadInstruments();
this.utilsDataService.getInstruments$()
.pipe(
takeUntil(this.destroyed$)
).subscribe(i => {
if (!!i) {
this.instruments = i;
}
})
}
ngOnInit(): void {
}
addInstrument() {
if (this.addInstrumentValid()) {
this.userInstruments.push("");
}
}