Remember that an li
element cannot be a direct child of a div element - only a ul
element can be the direct parent of an li
. The correct approach is to nest the content inside the repeating li and use an ng-container
with an *ngIf
directive to conditionally display the content if the item is selected.
I have considered your method for determining the selected item, but there are more efficient ways to achieve this.
Keep in mind that spans are inline-level elements, so you will need to style them properly for correct display and spacing. Using flex properties like setting display: flex on the li and justify-content: space-between can help separate out the spans effectively.
<ul class="meus-items-list">
<li *ngFor = "let item of meusItems, let i=index" [ngClass]="{'selected':item[i] == i}">
<span> Name: {{item.item.name}}</span>
<span> Description: {{item.item.description}}</span>
<ng-container *ngIf="item[i] == i">
<select class="custom-select">
<option *ngFor =" let soldier of mySoldiers"> {{soldier.soldier.name}}</option>
</select>
<button >Click me</button>
</ng-container>
</li>
</ul>
You could also achieve this by nesting a ul / li inside the main li:
<ul class="my-items-list">
<li *ngFor = "let item of myItems, let i=index" [ngClass]="{'selected':item[i] == i}">
<ul>
<li> Name: {{item.item.name}}</li>
<li> Description: {{item.item.description}}</li>
<li *ngIf="item[i] == i">
<select class="custom-select">
<option *ngFor =" let soldier of mySoldiers"> {{soldier.soldier.name}}</option>
</select>
<button >Click me</button>
</li>
</ul>
</li>
</ul>
An alternative approach would be using CSS alone - applying display none to the select and button elements in all li's except for the selected one. While this keeps these elements in the DOM, it may not be the ideal method.
li:not(.selected) select,
li:not(.selected) button {
display: none;
}