visibility:hidden causing issue with hiding empty option in IE dropdown

I am currently working on an Angular 11 application. On one of the pages, there are 2 radio buttons and a dropdown. The desired behavior is that whenever the radio button selection is changed, the dropdown value should be reset to empty.

The code provided works correctly in Chrome. However, in Internet Explorer, an empty option is still visible in the dropdown. It is preferred to not display an 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('');
}

Answer №1

I haven't tested it in Internet Explorer as it's not installed, but I did check in Edge and it's working perfectly!

You can remove the [value] binding since the default value can be set on the form control itself, eliminating the need for value here.

The line

this.myForm.get['City'].patchValue('');
appears to have invalid syntax, let's 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);

Check out the Stackblitz Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Bootstrap container with added page border

Allow me to explain the issue to the best of my ability: I have a design that needs to be implemented using bootstrap. I prefer to use only CSS and avoid JS/jquery. The content is contained within a bootstrap container that has two columns. The left gre ...

What issues arise from using ng-content within a web component?

I have a unique component structure for my website: <div (click)="popup.showAsComponent()"> <ng-content></ng-content> </div> Here is how I implement it: <my-web-component><button>Click!</button></my ...

Create an element that can be dragged without the need to specify its position as absolute

I am having an issue where elements I want to drag on a canvas are not appearing next to each other as expected. Instead, they are overlapping: To make these elements draggable, I am utilizing the dragElement(element) function from https://www.w3schools.c ...

Is it better to define a function within useEffect or externally?

What is the reason behind defining the fetchData function inside the useEffect instead of outside? Link: https://github.com/zeit/next.js/blob/canary/examples/with-graphql-faunadb/lib/useFetch.js import { useState, useEffect } from 'react' exp ...

Encountering a problem with the scope of child_process in Node

When utilizing the child_process module in Node.js with the fork method, I am able to send data to a specific file and receive a response. However, I am not logging this data to the console after receiving it from the execution process. The code in first. ...

Tips for simulating a configuration dependency using Proxyquire in TypeScript

Within my codebase, there exists a config.ts file that contains the following method: // Config interface is utilized to specify expected values export default function getConfig(): Config { return {amount: 50} } In a specific class located at ../src ...

I am unable to deliver an email to the mailbox

Whenever I try to send an email, I encounter an issue. In order to complete the registration process, a confirmation mail needs to be sent. The error message that I receive is: Callback must be a function at maybeCallback const fs = require(& ...

I encountered an error while attempting to import a file into Firebase Storage

I've been struggling to upload files from Firebase Storage and encountering errors despite reading the documentation and various blogs on the topic. I'm looking for the most effective approach to resolve this issue. import { storage } from ' ...

A guide on validating dates in Angular Ionic5 with the help of TypeScript

I have tried multiple solutions, but none seem to work when validating the current date with the date entered by the user. The date is passed from the user into the function parameters, but how do I perform validation? How can I validate the date? isToday( ...

Issue encountered: Inoperable binding when employing ko.mapping with two distinct models

I've been struggling to implement a drop-down select in conjunction with a table on a page using knockout bindings. The issue arises when I try to use the mapping options in the knockout binding plugin – either the drop-down or the table behaves inc ...

Mastering the art of filtering arrays in RxJS 6 using Observables and async functions

I am currently working with an Observable that returns data and is being bound asynchronously in HTML. Here is where I make the service call: this.ProductOptions = this.ProductService.fetchProduct(); The HTML binding looks like this: Productoptions | a ...

Receiving and monitoring events triggered by a Vue component that was dynamically mounted

I am currently mounting a Vue component dynamically within a mixin to incorporate the resulting HTML into a map popup. While everything is functioning correctly, I am facing an issue with listening to events emitted by the component. I am unsure of how to ...

Error: Unable to access the property of an undefined variable in Angular 4

Here is what I currently have in my code: <p *ngIf="model.something.satisfy"> Yes </p> <p *ngIf="!model.something.satisfy"> {{model.something.comments}} </p> The issue arises in the second line with the error message "Type ...

Is it necessary to unsubscribe within the subscribe callback function?

I've been searching for a straightforward solution to prevent memory leaks caused by not unsubscribing. Most of the time, I only need one response from the backend and then I want to unsubscribe. So why not call it within the callback? onSubmit(){ ...

What is the best way to ensure my buttons hide or display correctly when clicked?

I have been working on setting up an edit button that toggles the visibility of save and cancel buttons. However, I encountered a problem where all the buttons disappear when I click on the edit button. This issue did not occur with my other buttons, and t ...

Can I programmatically retrieve a comprehensive list of all global HTML attributes available?

Exploring the extensive list of global HTML attributes can be overwhelming, especially when considering how it continues to evolve with browser updates. Can JavaScript be leveraged to dynamically generate a complete list of these attributes without the ne ...

purging the setTimeout command

Although I am not very fluent in javascript/jquery, what I am attempting to achieve is to add a timeout to a mouseenter function. This part is not an issue for me, but I also want to clear the timeout if the user exits the element before the timeout comple ...

Creating a drawImg function on the HTML/JavaScript canvas

Attempting to duplicate a specified section of an image onto a canvas below, but finding that the mirrored section is resizing unexpectedly. For example, if given a map image and trying to replicate a building from it exactly below, why does the mirrored s ...

Troubleshooting "jest + enzyme + react16: The src attribute of <img> tag is not sending

Currently, I am utilizing jest along with enzyme for testing my react component titled "AnimateImage". This component includes an image element within it: import * as React from 'react'; import { PureComponent } from 'react'; interfac ...

Utilizing AngularJS to make an API call with $http method and handling a

I am attempting to make a call to my webservice using "$http". When I use "$ajax", it works fine. Here is an example of jQuery $Ajax working correctly: $.ajax({ type: "Get", crossDomain: true, contentType: "application/json; chars ...