0
votes

I am building a Reactive form with Angular 9, I have a dropdown, like so:

<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">

    ...

    <div class="form-group">
        <label class="small mb-1" for="isSigningUpFor">I'm signing up for</label>
        <select class="form-control py-4" id="isSigningUpFor"
            formControlName="signingUpFor" (change)="changeSigningUpFor($event)">
            <option value="Please select..." disabled selected>-- Select --</option>
            <option *ngFor="let opt of signingUpForOptions" [value]="opt.value"
                [selected]="(opt.isSelected == true)">{{ opt.text }} ({{ opt.isSelected }})
            </option>
        </select>

Here is the relevant code from the component:

registerForm = this.fb.group(
    {
        // other fields here
        signingUpFor: ['']
    },
);

signingUpForOptions = [
    {
        text: 'My Family',
        value: '1',
        isSelected: false
    },
    {
        text: 'My Sports Team',
        value: '2',
        isSelected: false
    },
    {
        text: 'The Lads',
        value: '3',
        isSelected: false
    }
];

changeSigningUpFor(e: any) {

    var thisValue = e.target.value;

    this.signingUpForOptions.forEach(x => {
        if (x.value == thisValue) {
            x.isSelected = true;
        } else {
            x.isSelected = false;
        }
    });

    this.registerForm.patchValue({
        signingUpFor: thisValue
    });
}

The dropdown displays fine, and shows the options. When I select one, changeSigningUpFor is running as expected, patching in the new value and setting the isSelected flags appropriately. I'm just not seeing the selected option in the UI, as shown below:

Gif showing selected value being set correctly, but nothing on the UI

The result is the same if I remove the onChange function call (ie selected value not showing). Removing opt.isSelected == true doesn't fix the issue either.

I'm not getting any errors in the console. I feel like an idiot here, this should be basic but I'm not used to working with forms in this way, what am I doing wrong?

Thanks

1

1 Answers

1
votes

Here's a working example. It might be your CSS, inspect the element to see if colors or visibility is affecting anything. Also check if you have ReactiveForms imported correctly and that you loaded it properly in your component.

https://stackblitz.com/edit/angular-ivy-9cl8gt?embed=1&file=src/app/app.component.ts