Angular Directive causing the generation of redundant elements

I am facing an issue with my Angular directive where it seems to be generating duplicate button and ul elements with the class "dropdown" after each specified element. The directive works perfectly when implemented using plain JavaScript. Can anyone identify why this duplication is occurring?

Below is my Directive code:

 // Import required modules
 import { Directive, ElementRef, Renderer2, HostListener, OnInit } from '@angular/core';

// Define the DropdownDirective class
@Directive({
  selector: '.dropdown-container'
})
export class DropdownDirective implements OnInit {

  constructor(private el: ElementRef, private _renderer: Renderer2) {

  }

  ngOnInit(){

    var dropdown = document.querySelectorAll('.customization-option');
    
    for (var i = 0; i < dropdown.length; i++) {
      var option = dropdown[i].querySelectorAll('option');
      var options = [];
      var drop;
      
      for (var x = 0; x < option.length; x++) {
        options.push(option[x].innerHTML);
      }

      drop = "<button>" + options[0] + "</button><ul class='dropdown'>";
      options.forEach(addOptions);
      drop += "</ul>";
      console.log(drop);
      dropdown[i].insertAdjacentHTML('afterend', drop)
    }

    function addOptions(value) {
      drop += "<li>" + value + "</li>";
    }


  }

  @HostListener('click') onClick(e) {

    var thisDrop = this.el.nativeElement;
    var opt = thisDrop.querySelector('.dropdown').children;
    var buttonDrop = thisDrop.parentElement.parentElement.querySelector('button');
    thisDrop.classList.toggle("active");

    for (var i = 0; i < opt.length; i++) {
      opt[i].addEventListener('click', function () {
        var optValue = this.innerHTML;
        buttonDrop.innerHTML = optValue;
        this.parentElement.classList.remove('active');
      });
    }

  }

}

In my template, I have implemented the directive as follows:

<form [formGroup]="storeRequest">
  <!-- Form content goes here -->
</form>

Although the directive mostly functions correctly, I am encountering a scenario where two buttons and two ul elements are being created after each dropdown selection. Any recommendations or insights on how to resolve this issue would be greatly appreciated. Thank you!

Answer №1

Upon reviewing your code, it appears that the .customization-option class is used in two of your <select> options. This results in a duplication of values when looping through

querySelectorAll('.customization-option')
with dropdown.length.

If you only need to access the class of the second <select> option, you can simply specify the index and retrieve the element.

document.querySelectorAll('.customization-option')[1];

Answer №2

Thank you, Angela for your guidance. I have made the necessary changes by updating

document.querySelectorAll('.customization-option');

to

var dropdown = this.el.nativeElement.querySelectorAll('.customization-option');

after setting up el as ElementRef.

constructor(public el: ElementRef, private _renderer: Renderer2) {
    this.el = el;
  }

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

Exploring Functions in Object Literal Notation in TypeScript: Why is the Context of 'this' Assigned as Type 'any'?

It appears that the question has been posed before, but my search yielded no results. The issue at hand seems rather straightforward. TypeScript integrates well with object literal notation, however, when methods are defined within, it struggles to handle ...

What is the best way to showcase nested array JSON data in an HTML Table?

https://i.stack.imgur.com/OHL0A.png I attempted to access the following link http://jsfiddle.net/jlspake/v2L1ny8r/7/ but without any success. This is my TypeScript code: var viewModel = function(data){ var self = this; self.orders = ko.observableArr ...

What are the benefits of using default ES module properties for exporting/importing compared to named module properties?

Currently studying the Material UI documentation, I came across this statement: It is noted in the example above that we used: import RaisedButton from 'material-ui/RaisedButton'; instead of import {RaisedButton} from 'material-ui&apo ...

Accurate function calls with multiple parameters in TypeScript

As a beginner in TypeScript and currently exploring its integration with AngularJS, I am facing a particular issue where the compiler is not detecting an error. In Angular, a resource provider typically includes a get() method that returns an instance of ...

Strategies for extracting information from the database

I have a pre-existing database that I'm trying to retrieve data from. However, whenever I run a test query, it always returns an empty value: { "users": [] } What could be causing this issue? entity: import {Entity, PrimaryGeneratedColumn, Col ...

After updating to Angular 7, an error was encountered: "TypeError: Unable to execute map function on ctorParameters"

After updating my Angular project to version 7, I encountered a new issue. When running "ng serve --open" from the CLI, I received the following error message: Uncaught TypeError: ctorParameters.map is not a function at ReflectionCapabilities._own ...

Define a module function that can be used externally

I am encountering an issue while trying to declare an external module that does not have existing typings. This library has a function that returns a string and takes no arguments. My attempt to define it in a .d.ts file is as follows: declare module "c ...

Using the Moment library in a NestJS application

I am integrating momentjs into my nestjs application and I want to ensure that my services can be tested effectively. To achieve this, I have included momentjs in my module setup as shown below: providers: [ { provide: 'MomentWrapper', ...

Tips for Using Typescript Instance Fields to Prevent Undefined Values

After creating a few Typescript classes, I encountered an issue where I would get an undefined error when trying to use them after instantiating. I experimented with initializing my fields in the constructor, which resolved the problem, but I don't t ...

Is it possible to assign a string literal type as a key in TypeScript mappings?

Is it possible to map a string literal type as a key in a new type? I attempted this, but it did not work as expected. const obj = { type: "key", actions: { a() {}, b() {}, }, } as const; /* Map to { key: { a() {}, b() {}, } */ t ...

Whenever comparing the types 'string[]' and 'DeliveryTypeEnum', this condition will consistently result in 'true' as there is no intersection between the two. This is highlighted by the error code ts(2367)

Hello everyone, I'm a junior developer and could use some assistance if (query.deliveryType && query.deliveryType != DeliveryTypeEnum.EITHER) { search.push({ terms: { "deliveryType.keyword&q ...

"Unveiling the Benefits of Converting Body to JSON String and Object in Angular 7

Why is it necessary to convert event.body into a JSON string and then parse it back into an object? this.excelFileService.upload(this.currentFileUpload).subscribe(event => { if (event.type === HttpEventType.UploadProgress) { this.progress ...

Stop pages from breaking in jsPDF due to text overflow

Currently, I am utilizing the jsPDF and html2canvas libraries to generate a PDF file from HTML content. An issue that I am facing is dealing with dynamic content where it is challenging to determine when each page ends. I have implemented a function to c ...

"Despite modifying the ID in the response data of Angular MongoDB, the request data ID remains unchanged

Having trouble with managing requests and responses, specifically when a customer tries to add multiple items of the same product but in different sizes. The initial step involves checking if the ID exists by using a count and an if statement. If it exists ...

Exploring the sharing of observables/subjects in Angular 2

UPDATE: After further investigation, it appears that the SharedService is being initialized twice. It seems like I may be working with separate instances, causing the .subscribe() method to only apply to the initiator. I'm not sure how to resolve this ...

Creating an Angular table row that can expand and collapse using ng-bootstrap components is a convenient and

I need assistance with an application I am developing, where I want to expand a table row to display details when it is clicked. The issue I am facing is that currently, all rows expand and show the data of the clicked row as seen in the image result below ...

When using npm link, it searches for the module in the src directory rather than the dist directory

In my experience with Angular CLI Builder, I have implemented a custom builder to extend the asset configuration in angular.json for libraries that have their own assets. To manage my workspace, I utilized nrwl. I created an Angular CLI builder library an ...

Issue with upgrading node from 12v to 16v: Trying to access a property that does not exist, specifically 'splice', within a circular dependency in module exports

After upgrading the node version from 12 to 16, we encountered a debugging console error. The 'Promises' are failing to resolve following this error, leading to the termination of further execution. (node:28112) Warning: Accessing non-existent p ...

How can you rearrange the order of objects in an array to only include duplicates?

https://i.sstatic.net/XwCDZ.png I don't want to alter the original order of objects in an array. However, I do need to retrieve items in a specific sequence when both the location and place are identical. I attempted a solution but it requires an ad ...

Tips for converting Javascript require to Typescript import using the const keyword

Recently, I've been attempting to import faktory_worker_node from github.com/jbielick/faktory_worker. The README provides the following instructions: const faktory = require('faktory-worker'); faktory.register('ResizeImage', asyn ...