My question is simple; why don't my class styles apply to dynamically created elements?
I am creating a search bar here where I generate an li per matching result, and append it to my ul. When I inspect the page, I see the classes are applied to the li's correctly, but the styles from the class itself aren't present. I hard coded a test li and it had the expected styles. What am I missing here in order to have my styles applied to these dynamically generated elements? Surely I don't have to assign every style for the li's in my typescript? Any explanation would be lovely, thank you all! (:
My HTML:
<div >
<h2>Step 1: Choose an Identity Provider (IDP)</h2>
<div >
<input
(focusout)="handleFocusOut()"
(input)="debounce(search, 300, $event)"
placeholder="Select Identity Provider"
autocomplete="off"
/>
<i ></i>
<ul id="search-options">
<li >IMG Salesforce</li>
</ul>
</div>
<!-- <i ></i>-->
</div>
My scss:
.section {
...
.search {
position: relative;
width: 300px;
.icon {
position: absolute;
right: 5px;
top: 3px;
}
input {
width: 300px;
}
ul {
color: red;
li {
cursor: pointer;
&:hover {
background-color: grey;
color: red;
}
.testing {
cursor: pointer;
&:hover {
background-color: grey;
color: red;
}
}
}
}
}
}
My TS:
let ul = document.getElementById('search-options');
this.displayServices.forEach((service) => {
let li = document.createElement('li');
li.classList.add('focusable', 'testing');
li.addEventListener('focusout', this.handleFocusOut);
const img = document.createElement('img');
img.src = this.getImgUrl(service);
img.width = 20;
img.height = 20;
img.style.margin = '0 10px';
li.innerHTML = `${service.name}`;
li.style.display = 'flex';
li.style.alignItems = 'center';
li.style.border = '.5px solid black';
li.style.padding = '8px 0';
li.prepend(img);
ul.appendChild(li);
});
CodePudding user response:
the classes are applied to the li's correctly, but the styles from the class itself aren't present
If you mean the focusable
and testing
classes, I don't see them in your SCSS.
CodePudding user response:
It's hard to be precise without seeing the whole tamale, but generally you should be getting your data in the .TS file and sending that data directly to the view. Your view should be creating those elements on the fly. Not shown in the answer here is the inline styles you were adding to the image and the LI tag - just do those in CSS.
Something like this:
TS:
this.someService.getData.subscribe(displayServices => {
this.displayServices = displayServices;
})
HTML:
<div >
<h2>Step 1: Choose an Identity Provider (IDP)</h2>
<div >
<input
(focusout)="handleFocusOut($event)"
(input)="debounce(search, 300, $event)"
placeholder="Select Identity Provider"
autocomplete="off" />
<i ></i>
<ul id="search-options">
<li *ngFor="service in displayServices"
(focusout)="handleFocusOut($event)">
<img [src]="getImgUrl(service)" />
{{service.name}}</li>
</ul>
</div>
<!-- <i ></i>-->
</div>