Search code examples
javascriptcssangulartypescriptinternet-explorer

display:none not hiding the empty option in dropdown in IE


I have running Angular 11 application. In the page I have 2 radio buttons and one dropdown. The behavior is that whenever I change the radio button selection, I want to reset dropdown value and show empty value in the dropdown.

Below code is working fine in Chrome. But in IE I can still see empty option in the dropdown. I don't want to show empty option in the dropdown list.

test.component.html

<form [formGroup]="myForm">
    <select [id]="control.Id" [formControlName]="control.Id" [value]="control.Value">
      <ng-container *ngFor="let item of control.Items">                        
         <option [value]="item.Value">{{item.Key}}</option>
       </ng-container>
       <option hidden disabled value="" style="display:none;"></option>
     </select>
</form>

test.component.ts

this.myForm.controls['City'].valueChanges.subscribe(this.onCityChange.bind(this));

onCityChange()
{
   this.myForm.get['City'].patchValue('');
}

Solution

  • I did not try in Internet Explorer due to it not being installed, but checked in Edge and it works fine!

    Remove the [value] binding, since you can set the default value on the form control itself, no need for value here

    The line this.myForm.get['City'].patchValue(''); Seems to be invalid syntax, we can rewrite this!

    import { CommonModule } from '@angular/common';
    import { Component } from '@angular/core';
    import { ReactiveFormsModule, FormGroup, FormControl } from '@angular/forms';
    import { bootstrapApplication } from '@angular/platform-browser';
    import 'zone.js';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [CommonModule, ReactiveFormsModule],
      template: `
        <form [formGroup]="myForm">
            <select [id]="control.Id" [formControlName]="control.Id">
              <ng-container *ngFor="let item of control.Items">                        
                <option [value]="item.Value">{{item.Key}}</option>
              </ng-container>
              <option hidden disabled value="" style="display:none;"></option>
            </select>
        </form>
        <button (click)="clear()">clear</button>
      `,
    })
    export class App {
      name = 'Angular';
      myForm = new FormGroup({
        test: new FormControl('One'),
      });
      control = {
        Id: 'test',
        Value: 'test',
        Items: [
          { Key: '1', Value: 'One' },
          { Key: '2', Value: 'Two' },
          { Key: '3', Value: 'Three' },
        ],
      };
    
      clear() {
        this.myForm?.get('test')?.patchValue('');
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo