Troubleshooting: Angular 6 Renderer2 Issue with Generating Dynamic DOM Elements for SELECT-Option

Currently, I am attempting to dynamically create a select option using Renderer2. Unfortunately, I am facing difficulties in creating the <Select></Select> element, but I can confirm that the <options> are being successfully created. Due to certain limitations, I regret that I am unable to share all of the code snippets.

The main issue revolves around the fact that the select element is not being created, and only the first element of the array is being displayed. However, when I console log it in ngOnInit(), I am able to see all elements without any errors popping up on the console.

Please find attached.

https://i.stack.imgur.com/VB2nq.png

I humbly request assistance and guidance in this matter. If possible, could someone provide a working demo or steer me in the right direction? After spending numerous hours researching, I stumbled upon this resource only.

    arr= ["AAA", "BBB", "CCC", "DDD", "EEE"];
    const select = this._rend.createElement('select');
  select.name = name;
  var option = this._rend.createElement('option');      
    this._rend.appendChild(select, option);
    this._rend.appendChild(option, document.createTextNode(''));
  
    arr.forEach( aaaa=>{ 
        option = this._rend.createElement('option');        
        this._rend.appendChild(option, document.createTextNode(aaaa));
        if (aaaa === value)
          option.selected = true;
            this._rend.appendChild(select, option);
        
    }) 

Please feel free to share alternative solutions if you deem mine inadequate.

A heartfelt thank you to everyone willing to assist.

Answer №1

Take a look at this code snippet for creating select options in stackblitz:

class AppComponent {
   arr = ["AAA", "BBB", "CCC", "DDD", "EEE"];
   value = 'BBB'

     constructor(private el: ElementRef, private renderer: Renderer2) {
       const select = renderer.createElement('select');
       select.name = name;
       var option = renderer.createElement('option');
       renderer.appendChild(select, option);
       renderer.appendChild(option, document.createTextNode(''));

       this.arr.forEach(aaaa => {
         option = renderer.createElement('option');
         renderer.appendChild(option, document.createTextNode(aaaa));
         if (aaaa === this.value) option.selected = true;
         renderer.appendChild(select, option);

       })
       renderer.appendChild(this.el.nativeElement, select);
     }
}

This class creates a select element using Renderer2, then appends the options created with Renderer2 to the select element.

Finally, the select element is appended to the AppComponent's nativeElement.

Flow:

 Created `select`
 |
 V
 Appended `Option` to select
 |
 V
 Appended `select` to the AppComponent host element

Check out the code on StackBlitz

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

Is it possible to indicate the base type for a generic function?

Is it possible to define the generic type T as an Object rather than a primitive type like number or string? For example, this clone function should only accept Objects as input. It will destructure the input object o, set its prototype back to that of th ...

Enhancing performance with React.memo and TypeScript

I am currently developing a react native application. I am using the Item component within a flatlist to display data, however, I encountered an error in the editor regarding the second parameter of React.memo: The error message reads: 'Type 'bo ...

Unveiling the Power of USSD Codes with Ionic Typescript: A Comprehensive Guide

Currently diving into the world of Ionic 2 Framework, I find myself on a quest to discover how to execute USSD codes in Ionic using Typescript. Any guidance or assistance from the community would be greatly appreciated! ...

Changing the names of the remaining variables while object destructuring in TypeScript

UPDATE: I have created an issue regarding this topic on github: https://github.com/Microsoft/TypeScript/issues/21265 It appears that the syntax { ...other: xother } is not valid in JavaScript or TypeScript, and should not compile. Initial Query: C ...

Transforming two child arrays within an object into a single array using Ramda

I am looking to transform an object into an array. The object I have is structured like this: const data = { t1: [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ], t2: [ {" ...

Angular TextInput Components don't seem to function properly when dealing with arrays

I am trying to create a collection of text input components with values stored in an array. However, when using the following code, the values seem to be placed incorrectly in the array and I cannot identify the bug. <table> <tr *ngFor="let opt ...

The IDE is showing an error, but Jest is able to run it flawlessly

I recently created a Jest unit test for a TypeScript function called checkEmail, which internally uses showAlert. The showAlert function in the utils.ts file looks like this: export const showAlert = (message: string) => { toast(message); }; In my ...

What is the process for including a new item in the p-breadcrumb list?

Having trouble getting my code to add a new item to the p-breadcrumb list on click. Any assistance would be greatly appreciated. Thank you in advance! Check out the live demo here ngOnInit() { this.items = [ {label: 'Computer'}, ...

What is the best way to convert an array of data into a dataset format in React Native?

Within my specific use case, I am seeking to reform the array structure prior to loading it into a line chart. In this context, the props received are as follows: const data = [26.727, 26.952, 12.132, 25.933, 12.151, 28.492, 12.134, 26.191] The objective ...

Issue with NgModule in Angular application build

I'm facing an issue with my Angular application where the compiler is throwing errors during the build process. Here's a snippet of the error messages I'm encountering: ERROR in src/app/list-items/list-items.component.ts:9:14 - error NG6002 ...

The server has access to an environment variable that is not available on the client, despite being properly prefixed

In my project, I have a file named .env.local that contains three variables: NEXT_PUBLIC_MAGIC_PUBLISHABLE_KEY=pk_test_<get-your-own> MAGIC_SECRET_KEY=sk_test_<get-your-own> TOKEN_SECRET=some-secret These variables are printed out in the file ...

The ko.mapping function is throwing an error because it cannot access the property 'fromJS' which is undefined

I am currently exploring typescript and attempting to integrate knockout.mapping into my project, but I'm facing some challenges. Despite installing the necessary libraries for knockout and knockout.mapping, along with their respective "@types" decla ...

Troubleshooting Angular 6: Issues with Route Guards not functioning as expected

Striving to enhance frontend security by restricting access to specific IDs. The goal is to redirect anyone trying to access routes other than /login/:id to a page-not-found error message if not already logged in, but encountering some issues. Below are t ...

Is it possible to use Angular signals instead of rxJS operators to handle API calls and responses effectively?

Is it feasible to substitute pipe, map, and observable from rxjs operators with Angular signals while efficiently managing API calls and their responses as needed? I attempted to manage API call responses using signals but did not receive quick response t ...

The TypeScript error code TS2339 is indicating that the 'modal' property is not recognized on the type 'JQuery'

I'm currently utilizing Typescript with AngularJS and have encountered an issue with modals when using the typed definition of jQuery library. The specific error message I am receiving is: 'error TS2339: Property 'modal' does not exist ...

Is there a way to tally up the overall count of digits in a number using TypeScript?

Creating a number variable named temp in TypeScript: temp: number = 0.123; Is there a way to determine the total count of digits in a number (in this case, it's 3)? ...

Can a form component be recycled through the use of inheritance?

Greetings to the Stackoverflow Community, As I delve into this question, I realize that examples on this topic are scarce. Before diving into specifics, let me outline my strategy. I currently have three pages with numerous FormGroups that overlap signif ...

What are the steps to set up tsline in settings.json file?

Currently utilizing visual studio code Upon searching for the settings.json file, the contents appear as follows: { "liveServer.settings.donotVerifyTags": true, "liveServer.settings.donotShowInfoMsg": true, "javascript ...

Discover the power of TypeScript's dynamic type inference in functions

Below is a function that selects a random item from an array: const randomFromArray = (array: unknown[]) => { return array[randomNumberFromRange(0, array.length - 1)]; }; My query pertains to dynamically typing this input instead of resorting to u ...

TS18047 jest error: "object may be null"

I'm currently working on a test (jtest) for an angular component, but it keeps failing due to this particular error. Any thoughts on how to resolve this? :) it("should require valid email", () => { spectator.component.email.setValue( ...