How to work with Dropdown Select element in Typescript

In a webpage, dropdown is represented by Select HTML element. When you have to work with dropdown element in Typescript, you will use following strongly typed objects.

  • HTMLSelectElement: This represents Select element
  • HTMLOptionsCollection: This represent collection of dropdown items
  • HTMLOption: Each Option element in dropdown

Following code shows how a dropdown is used in Typescript.

private manufacturerAdded(e: CustomEvent) {
        const manufacturerService = new ManufacturerService();
        manufacturerService.getManufacturers().then((results) => {
            const selectElement = this.containerElement.querySelector("#selectManufacturer") as HTMLSelectElement;
            const selectedManufacturers: number[] = [];
            for (let i = 0; i < selectElement.selectedOptions.length; i++) {
                const option = selectElement.options[i];
                if (option.selected) {
                    selectedManufacturers.push(parseInt(option.value));
                }
            }
            selectElement.options.length = 0;

            const placeholderOption = document.createElement("option") as HTMLOptionElement;
            placeholderOption.value = `0`;
            placeholderOption.text = "Select Manufacturer";
            selectElement.options.add(placeholderOption);

            for (let i = 0; i < results.length; i++) {
                const option = document.createElement("option") as HTMLOptionElement;
                option.value = `${results[i].id}`;
                option.text = results[i].name;
                option.selected = e.detail.id === results[i].id;
                selectElement.options.add(option);
            }
        });
    }

Above code does not use jQuery or any library. The code uses native DOM elements with native javascript implementation provided by browser. The key to using strongly typed objects is casting the HTML element to correct Typescript typings. Above code queries Select element from the page and then casts it to HTMLSelectElement. The implementation is used to repopulate the dropdown list with data received from a microservice. You can a set length property of HTMLOptionsCollection to remove all dropdown elements before repopulating the list. After the list has been cleared, the implementation creates new HTMLOptionElement objects and adds them to HTMLSelect element.

comments powered by Disqus

Search

Social

Weather

19.1 °C / 66.3 °F

weather conditions Clouds

Monthly Posts

Blog Tags