I am currently developing a basic to-do app using Angular4. The setup of the app is structured as follows:
Form Component: Responsible for adding items to the to-do list
Item Component: Represents individual to-do items
App Component: Contains a *ngFor loop to display all the to-do items.
I have implemented a new button in the item component to delete the respective item. However, I am facing difficulty in determining the correct index number to splice or filter out the item.
You can access the GitHub repository here
Here are the code snippets:
<app-navbar></app-navbar>
<div class="container">
<app-form (itemAdded)="onItemAdded($event)"></app-form>
<div class="row">
<div class="col-md-3 mb-3"
*ngFor="let item of toDoList; let i=index">
<app-item
[listItem]="item"
(itemDeleted)="onItemDeleted($event)"></app-item>
</div>
</div>
</div>
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
toDoList = [
{
name: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
}
];
onItemAdded(itemData: {itemName: string}){
this.toDoList.push({
name: itemData.itemName
});
}
onItemDeleted(index: number){
this.toDoList.splice(index, 1);
}
}
form.component.html:
<div class="title">
<h1 class="display-4">{{ title }}</h1>
</div>
<div class="input-group">
<input type="text" class="form-control" [(ngModel)]="newItem">
<span class="input-group-btn">
<button class="btn btn-success" type="button" (click)="onAddItem()">
<fa name="plus"></fa>
</button>
</span>
</div>
form.component.ts:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
@Output() itemAdded = new EventEmitter<{itemName: string}>();
title = 'To-Do List';
newItem = '';
constructor() { }
ngOnInit() {
}
onAddItem(){
this.itemAdded.emit({itemName: this.newItem});
}
}
item.component.html:
<div class="task">
<div class="mb-5 d-flex justify-content-between">
<fa name="circle-o" size="3x"></fa>
<button type="button" name="delete" class="btn btn-danger align-self-end" (click)="onDeleteItem()"><fa name="trash"></fa></button>
</div>
{{item.name}}
</div>
item.component.ts:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-item',
templateUrl: './item.component.html',
styleUrls: ['./item.component.css']
})
export class ItemComponent implements OnInit {
@Input('listItem') item: {name: string};
@Output() itemDeleted = new EventEmitter<{index: number}>();
constructor() { }
ngOnInit() {
}
onDeleteItem() {
this.itemDeleted.emit() //need help with this
}
}