Implementasi Template Driven Form – 3

Pada modul ini kita akan memperbaiki form shopping-edit.component.html agar button ditampilkan sesuai status edit atau add new item.

Buka file shopping-edit.component.html, kemudian tambah code untuk mengubah tulisan button dengan memeriksa property isEdit.

<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">Del</button>
                    <button class="btn btn-primary" type="button">Clear</button>
                </div>
            </div>
        </form>
    </div>
</div>

Kemudian buka file shopping-list.service.ts, kita tambahkan fungsi untuk melakukan update.

Perlu kami akui, penamaan property neInggredietAdded tidak sesuai konteks karena sekarang digunakan juga untuk proses update. Jika Anda ingin mengubah, silakan lakukan perubahan.

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

export class ShoppingListService{
    newInggredientAdded = new Subject<Ingredient[]>();
    //tambahkan untuk shopping list edit.
    startEdit = new Subject<number>();

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

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

    //method untuk mengambil data ingredient berdasarkan id.
    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());
    }

    //tambahkan method untuk melakukan update ingredient.
    updateIngredient(idx: number, ingredient: Ingredient){
        this.ingredients[idx] = ingredient;
        this.newInggredientAdded.next(this.ingredients.slice());
    }
}

Buka file shopping-edit.component.ts, lalu tambahkan code untuk melakukan update.

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
        });
      }
    );
  }

  //tambahkan code untuk melakukan update ingredient
  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);
    }
  }

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

Sesuai ekspektasi, kita sudah bisa melakukan update ingredient.

Pada modul berikutnya kita akan tambahkan fitur untuk reset form setelah proses add atau update. Dan menambahkan fitur Del dan Clear.

Sharing is caring:

Leave a Comment