As I venture into the world of Angular, I encountered a snag with *ngIf
Upon launching the app, *ngIf="item.done"
works correctly in showing or hiding the element based on whether the ToDo item
is marked as done
. However, upon clicking on the element, despite the change in the done
state (confirmed by console logging), the element does not vanish. Instead, regardless of the state change, if it goes back to being done
, the same element is created once more.
Check out the onTick()
function, responsible for toggling the item.done
state
item.done = false
→ Hidden Screenshot- 1st click →
item.done = true
→ Shown - 2nd click →
item.done = false
→ Shown - 3rd click →
item.done = true
→ Shown TWICE Screenshot
// MOCK DATA
import { Item } from './item';
export const ITEMS: Item[] = [
{id: 1, title: 'Buy Milk', done: false},
{id: 2, title: 'Do Math', done: true},
{id: 3, title: 'Cook food', done: false}
]
// THE COMPONENT TypeScript
import { Component, OnInit } from '@angular/core';
import { ITEMS } from './mock-items';
import { Item } from './item';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
items: Item[] = [];
constructor() {
this.items = ITEMS
}
ngOnInit() {
}
onTick(item) {
console.log('Item was: ', item.done)
item.done = !item.done
console.log('Item became: ', item.done)
}
}
<!-- THE COMPONENT HTML -->
<div class="list">
<div class="list--header">
<h1>List</h1>
</div>
<div class="list--content">
<ul class="list--items">
<li *ngFor="let item of items">
<div class="checkbox" (click)="onTick(item)">
<input type="checkbox" style="display: none">
<i *ngIf="item.done" class="tick fas fa-check"></i>
</div>
{{item.title}}
</li>
</ul>
</div>
<div class="list--footer">
</div>
</div>