I'm trying to create a toggle for the only input you see inside of the span so I could hide it once I click the "Edit" button again. Any idea on how to make it work?
HTML:
<h2>Universities</h2>
<ul *ngFor="let item of items; let i = index">
<li>
{{ item }}
<button
type="button"
class="btn btn-default"
style="background-color: #ffe4b5"
(click)="editIndex = i"
>
Edit
</button>
<span>
<input *ngIf="editIndex === i" />
</span>
<span>
<button
type="button"
class="btn btn-default"
style="background-color: #90ee90"
>
Save
</button>
</span>
</li>
</ul>
TS:
items: string[] = [];
editIndex: number | undefined;
showInput: boolean = false;
showData(index: any) {
console.log(this.items[index]);
}
(I created ShowData just to test if the index of the item works in the console when I click it)
CodePudding user response:
You need to set the editIndex
on click:
<!-- component template -->
<button type="button" (click)="setEditIndex(i)" class="btn btn-default" style="background-color: #ffe4b5">
// component
setEditIndex(index: number): void {
this.editIndex = index;
}
Your condition check in the template for editIndex === i
should work after that.
CodePudding user response:
You can toggle the editIndex in the click function
In html
<button
type="button"
class="btn btn-default"
style="background-color: #ffe4b5"
(click)="toggle()"
>
Edit
</button>
<span>
<input *ngIf="editIndex" />
</span>
In .ts
editIndex = false;
toggle() {
this.editIndex = !this.editIndex
}