Angular4 ToDoList

In angular4 you can easily create todolist iam not saving data in browser local storage or any other database this is to show how we can simply create todolist in angular4. Demo

app.module.cs
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule }   from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
app.component.ts
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 _submit:boolean = false; 
 item:string;
 items:Array<string> = ['USA','India','Canada','Afghanistan'];
 addItem(){
   if(this.item){
      this.items.unshift(this.item)
    }
    else{
      this._submit = true;
    }
 }
 deleteItem(index){
  for(let i =0; i <= this.items.length; i++){
        if(i == index){
            this.items.splice(i,1)
        }
 }
 this.item= ""
}
editItem(index){
   for(let i =0; i <= this.items.length; i++){
      if(i == index){
            this.item = this.items[i]
        }
  
 } 
}
 updateItem(index){
   if(this.item){

  for(let i =0; i <= this.items.length; i++){
         if(i == index){
              this.items[i] = this.item;
        }
  
 }
   }
   else{
     this._submit = true;
      }
  
 }

}
app.component.html

<div class="container"><br>
   <form #f="ngForm" (ngSubmit)="addItem()">
  <div class="row">
   
  <div class="col-md-10"><input type="text" #itemVar=ngModel [(ngModel)]="item" name="item"  class="form-control" placeholder="Add Country" required>
     <div *ngIf="itemVar.invalid && (itemVar.dirty || itemVar.touched) || itemVar.invalid && _submit" class="alert alert-danger">
          <div *ngIf="itemVar.errors.required">
            Country is required
         </div>
        </div>
  </div>
  <div class="col-md-2"><button type="submit" class="btn btn-primary">Add</button></div>

</div></form><br>
 <div class="row">
<div class="col-md-12"><ul class="list-group">
  <li *ngFor= "let item of items; let i = index " class="list-group-item d-flex justify-content-between align-items-center">
    {{item}}
    <div class="btn-group" role="group" aria-label="Basic example">

  Delete
  Edit
  Update
    </div>
  </li>

</ul></div></div>
</div>

Demo

Leave a Reply

Your email address will not be published. Required fields are marked *