I am currently working on a project in Angular 9.1.13, hosted on Centos 7.
One of the components in my project contains static HTML code, shown below:
<ul id="myUL">
<li><span class="caret">Top 1</span>
<ul class="nested">
<li>Sub 1</li>
<li>Sub 2</li>
</ul>
</li>
</ul>
The CSS styling for this component is as follows:
ul, #myUL {
list-style-type: none;
}
#myUL {
margin: 0;
padding: 0;
}
.caret {
cursor: pointer;
user-select: none;
}
.caret::before {
content: "\25B6";
display: inline-block;
margin-right: 6px;
}
.caret-down::before {
transform: rotate(90deg);
}
.nested {
display: none;
}
.active {
display: block;
}
In the ngOnInit()
method of the component, the following JavaScript code is executed:
...
const toggler = document.getElementsByClassName('caret');
let i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener('click', function() {
this.parentElement.querySelector('.nested').classList.toggle('active');
this.classList.toggle('caret-down');
});
}
...
Although everything works well with the pre-defined HTML structure, issues arise when trying to dynamically generate the list content.
To achieve dynamic content generation, the HTML structure is modified as follows:
<ul id="myUL"></ul> <!-- intentionally left empty -->
Prior to the mentioned code within the ngOnInit()
, the following snippet is added:
...
const myUL = document.getElementById('myUL');
myUL.innerHTML =
'<li><span class="caret">Top 1</span><ul class="nested"><li>Sub 1</li><li>Sub 2</li></ul></li>';
// Continue executing the previous code
...
Trouble arises from the fact that the dynamic content does not retain collapsible functionality or proper styling, despite having click events properly attached to the relevant elements:
My goal is to dynamically generate the list while maintaining the same interactive behavior and style seen in the initial screenshot.