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!