0

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 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Michael, turns out it was my CSS and I'm a moron :)
Glad to be of help :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.