Implementasi Template Driven Form – 4

Pada modul ini kita akan melakukan beberapa hal, yaitu reset form dan menambahkan fitur pada button clear dan del.

Reset Form

Untuk melakukan form reset, dapat dilakukan sesudah proses add atau update.

Buka file shopping-edit.component.ts, lalu ubah code onAddItem().

  onAddItem(form : NgForm){
    const value = form.value;
    const newIngredient = new Ingredient(value.name, value.amount);
    if (this.isEdit) {
      this.shoppingListServ.updateIngredient(this.editIdx, newIngredient);
    }else{
      this.shoppingListServ.addIngredient(newIngredient);
    }
    //tambahkan code untuk reset form dan reset property isEdit
    this.isEdit = false;
    form.reset();
  }

Menambahkan Fungsi pada button Clear

Buka file shopping-edit.component.html, pertama kita akan modifikasi button clear.

Tambahkan click listener pada button Clear.

<button class="btn btn-primary" type="button" (click)="onClear()">Clear</button>

Kemudian tambahkan method untuk handling event click pada shopping-edit.component.ts.

 onClear(){
  this.isEdit = false;
    this.slForm.reset();
}

Menambahkan Fungsi pada button Del

Buka file shopping-edit.component.html, pada button Del, tambahkan click listener dan ngIf untuk memastikan mode adalah edit.

<button class="btn btn-danger me-1" type="button" (click)="onDel()" *ngIf="isEdit">Del</button>

Buka file shopping-list.service.ts, tambahkan code untuk melakukan delete ingredient.

deleteIngredient(idx: number){
    this.ingredients.splice(idx, 1);
    this.newInggredientAdded.next(this.ingredients.slice());
}

Kemudian buka file shopping-edit.component.ts, tambahkan method untuk handlng event click.

onDel(){
  this.shoppingListServ.deleteIngredient(this.editIdx);
  this.onClear();
}

Sampai disini kita sudah berhasil menambahkan fungsi pada button Del dan Clear serta melakukan form reset.

Berikut isi lengkap file shopping-edit.component.html.

<div class="row">
    <div class="col-xs-12">
        <form (ngSubmit)="onAddItem(f)" #f="ngForm">
            <div class="row">
                <div class="col-sm-5 form-group">
                    <label for="name" class="form-label">Name</label>
                    <input type="text" class="form-control" id="name" name="name" ngModel required>
                </div>
                <div class="col-sm-2 form-group">
                    <label for="amount" class="form-label">Amount</label>
                    <input type="number" class="form-control" id="amount" name="amount" ngModel required pattern="^[1-9]+[0-9]*$">
                </div>            
            </div>
            <div class="row mt-2">
                <div class="col-xs-12">
                    <button class="btn btn-success me-1" type="submit" [disabled]="f.invalid">
                        {{isEdit ? 'Update' : 'Add' }}
                    </button>
                    <button class="btn btn-danger me-1" type="button" (click)="onDel()" *ngIf="isEdit">Del</button>
                    <button class="btn btn-primary" type="button" (click)="onClear()">Clear</button>
                </div>
            </div>
        </form>
    </div>
</div>

File shopping-edit.component.ts.

import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Subscription } from 'rxjs';
import { Ingredient } from 'src/app/shared/ingredient.model';
import { ShoppingListService } from '../shopping-list.service';

@Component({
  selector: 'app-shopping-edit',
  templateUrl: './shopping-edit.component.html',
  styleUrls: ['./shopping-edit.component.css']
})
export class ShoppingEditComponent implements OnInit, OnDestroy {
  @ViewChild('f', {static:false}) slForm! : NgForm;
  shoplistSubc! : Subscription;
  isEdit = false;
  editIdx = 0;
  editIngredient! : Ingredient;

  constructor(private shoppingListServ : ShoppingListService) { }

  ngOnInit(): void {
    this.shoplistSubc = this.shoppingListServ.startEdit.subscribe(
      (idx : number)=>{
        this.isEdit = true;
        this.editIdx = idx;
        this.editIngredient = this.shoppingListServ.getIngredient(idx);
        this.slForm.setValue({
          name : this.editIngredient.name,
          amount : this.editIngredient.amount
        });
      }
    );
  }

  onAddItem(form : NgForm){
    const value = form.value;
    const newIngredient = new Ingredient(value.name, value.amount);
    if (this.isEdit) {
      this.shoppingListServ.updateIngredient(this.editIdx, newIngredient);
    }else{
      this.shoppingListServ.addIngredient(newIngredient);
    }
    //tambahkan code untuk reset form dan reset property isEdit
    this.isEdit = false;
    form.reset();
  }

  onClear(){
    this.isEdit = false;
    this.slForm.reset();
  }

  onDel(){
    this.shoppingListServ.deleteIngredient(this.editIdx);
    this.onClear();
  }

  ngOnDestroy(): void {
    this.shoplistSubc.unsubscribe();
  }
}

File shopping-list.service.ts.

import { Subject } from "rxjs";
import { Ingredient } from "../shared/ingredient.model";

export class ShoppingListService{
    newInggredientAdded = new Subject<Ingredient[]>();
    startEdit = new Subject<number>();

    private ingredients : Ingredient[] = [
        new Ingredient("Oreo", 1),
        new Ingredient("Tepung", 1),
      ];    

    getIngredients(){
        return this.ingredients.slice();
    }

    getIngredient(idx : number){
        return this.ingredients[idx];
    }

    addIngredient(ingredient : Ingredient){
        this.ingredients.push(ingredient);
        this.newInggredientAdded.next(this.ingredients.slice());
    }

    addIngredients(ingredients: Ingredient[]){
        this.ingredients.push(...ingredients);
        this.newInggredientAdded.next(this.ingredients.slice());
    }

    updateIngredient(idx: number, ingredient: Ingredient){
        this.ingredients[idx] = ingredient;
        this.newInggredientAdded.next(this.ingredients.slice());
    }

    //method untuk delete ingredient
    deleteIngredient(idx: number){
        this.ingredients.splice(idx, 1);
        this.newInggredientAdded.next(this.ingredients.slice());
    }
}

Sharing is caring:

Leave a Comment