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

Issues with React's onSelect event functionality are persisting

Is there an event handler in React for the onSelect statement? For example, when a user highlights some text within a paragraph using their mouse, is there a way to trigger an event that extracts the highlighted text? import React, { Component } from &apo ...

"Troubleshooting alert: Encounter an error message saying 'process is not defined' when attempting to load the grpc package using proto-loader and grpc-js within a

Looking for help with integrating a typescript Vue.js component that needs to make a grpc call. The proto file can be found here: https://github.com/floydjones1/ts-node-grpc/blob/main/proto/random.proto Here is the component.vue code snippet: <script ...

Encountering an issue with finding the module `scheduler/tracing` in React Native

Encountering an error during the react-native run-android process: Error: Unable to resolve module `scheduler/tracing` from `/Users/miftahali/projects/react/appscustomec/node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js`: Module ...

Sharing data between parent and child components in Angular using ngrx

Currently, I am implementing @ngrx router and facing a scenario where one of the routes includes child routers for passing route parameters. Here is how it looks: { path: '/browse', component: BrowseComponent, children: [ { path: ':ca ...

Executing a post request using axios

Having some trouble with a post request using axios and it's refusing to cooperate. Here is the specific request I need to make. This is what I attempted: await axios.post( 'https://api.searchads.apple.com/api/v4/campaigns/XXXX/adgroups/targ ...

Tips for specifying the return type of app.mount()

Can I specify the return value type of app.mount()? I have a component and I want to create Multiple application instances. However, when I try to use the return value of mount() to update variables associated with the component, TypeScript shows an error ...

Configuring NextJs routes with multiple parameters

Seeking guidance on structuring files in Nextjs for handling multiple URL parameters. Can anyone offer advice? The given URL structure is: /api/upload?file=${filename}&fileType=${fileType} This is the current file structure: app api upload ...

Creating an interactive form in Angular2 using *ngFor, implementing two-way data binding with [(ngModel)], and including form validation

Challenge Description I'm currently working on developing a dynamic form that can update parts of the interface based on changes in the underlying model: When a user clicks a button, a new entity is added to the internal list of components and a ne ...

JavaScript alert: element does not exist

Check out my code snippet below. The inline JavaScript alert works fine, but the external one isn't firing. Every time I reload the page, I'm greeted with a console error message saying "TypeError: tileBlock is null". Any suggestions on how to re ...

Accessing a resource file from a compiled JAR archive

One issue that I am facing involves the project structure of my Maven Java project. It follows a typical layout: src/main/java - project .java files src/main/resources - project resources (log4j2.xml) src/test/java - .java files for tests src/test/r ...

Design with Internal Elements

Seeking a pattern similar to the code snippet provided below. Interested in learning how to create MyComponent. render(){ <MyComponent> <MyComponent.Something> These children will be displayed </MyComponent.Something> <MyC ...

Starting the Android System Magnifier with a Click: A Step-by-Step Guide

Is there a way to incorporate a magnifying glass into an HTML page using jQuery or within an Android app? Ideally, it would be for a single picture. In my application, I am displaying an HTML file from my assets in a webview. The HTML page utilizes jQuery ...

Display a text field upon clicking on a specific link

I am trying to create a text field that appears when a link is clicked, but I haven't been able to get it right yet. Here is what I have attempted: <span id="location_field_index"> <a href="javascript:void(0)" onclick="innerHTML=\"< ...

Dynamic content loading in Angular through HTML upon clicking

In the process of developing an Angular store, I aim to create anchor tags for each product so that clicking on a tag will display the selected product information in an HTML template below. Below is the current code snippet: (function() { var app = an ...

Adding information to a database by utilizing Jquery, Ajax, and PHP

Trying to use ajax to submit data to a database has been a challenge for me. Even with a simple code test, I can't seem to make it work. Here is the HTML/ajax code snippet: <?php include("osb.php");?> <script type = "text ...

Accessing store state in axios plugin with Nuxt.js

I've encountered a problem where I have a token stored, but I'm struggling to access it in my axios plugin while using Nuxt.js. In the past with just Vue, it was simple to import the store and access the token. However, I'm having difficulty ...

send multiple textbox values to controller in CodeIgniter

I am new to Codeigniter and I'm facing some difficulties in understanding how to accomplish a task. In my view page, there are five rows generated using a for loop. Each row consists of two select boxes and two input boxes. I don't know how to re ...

Steps to have index.html display when running the build command in a Svelte project:

Greetings everyone, I'm brand new to using Svelte and have a question that's been on my mind. I recently developed a small app in Svelte that works perfectly fine during development. However, when I run npm run build for production, the output ...

Encountered an error while parsing a module in React: Unexpected token

After deciding to incorporate the npm package react-radio-buttons into my project, I encountered an error upon installation and implementation in my component: ./node_modules/react-radio-buttons/index.jsx 80:6 module parse failed: Unexpected token (80:6) ...

Is it possible to pass the chart type as a property when using vue-chart.js?

Is it possible to pass the chart type as a property with vue-chart.js? I would love to see some example source code. Can you please provide guidance on this? ...