Menggunakan Local References dan @viewChild

Kita akan membahas penggunaan Local References dan @ViewChild pada component shopping-list.

Perhatian: akan diubah implementasi menjadi FormControl pada modul pembahasan Form. Tujuan modul ini untuk membahas penggunaan references dan @viewchild.

Proses yang dilakukan adalah, component akan menangkap perubahan pada input type menggunakan local reference dan @ViewChild.

Kemudian data ingredient yang sudah diperoleh dikirimkan ke parent component, untuk ditambahkan kedalam array ingredients dan kemudian ditampilkan.

Buka file shopping-edit.component.html, tambahkan local reference untuk input type text. Kemudian tambahkan juga event click pada Add button.

<div class="row">
    <div class="col-xs-12">
        <form>
            <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" #nameInput>
                </div>
                <div class="col-sm-2 form-group">
                    <label for="amount" class="form-label">Amount</label>
                    <input type="number" class="form-control" id="amount" #amountInput>
                </div>            
            </div>
            <div class="row mt-2">
                <div class="col-xs-12">
                    <button class="btn btn-success me-1" type="submit" (click)="onAddItem()">
                        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>

Buka file shopping-edit.component.ts kemudian tambahkan

  • Decorator @ViewChild untuk menangkap perubahan pada local reference.
  • @Output EventEmiter untuk membroadcast data ke parent component.
  • Method untuk menangani event onClick.
import { Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
import { Ingredient } from 'src/app/shared/ingredient.model';

@Component({
  selector: 'app-shopping-edit',
  templateUrl: './shopping-edit.component.html',
  styleUrls: ['./shopping-edit.component.css']
})
export class ShoppingEditComponent implements OnInit {
  @ViewChild('nameInput', {static:false}) nameInputRef!: ElementRef;
  @ViewChild('amountInput', {static:false}) amountInputRef!: ElementRef;
  @Output() ingredientAdded = new EventEmitter<Ingredient>();

  constructor() { }

  ngOnInit(): void {
  }

  onAddItem(){
    const _name = this.nameInputRef.nativeElement.value;
    const _amount = this.amountInputRef.nativeElement.value;
    const newIngredient = new Ingredient(_name, _amount);
    this.ingredientAdded.emit(newIngredient);
  }
}

Selanjutnya buka file shopping-list.component.html, tambahkan code untuk menangkap data yang di-emit.

<div class="row">
    <div class="col-xs-10">
        <app-shopping-edit (ingredientAdded)="onIngredientAdded($event)"></app-shopping-edit>
        <hr>
        <ul class="list-group">
            <a class="list-group-item" style="cursor:pointer" *ngFor="let ingredient of ingredients">
                {{ingredient.name}} ({{ingredient.amount}})
            </a>
        </ul>
    </div>
</div>

Kemudian buka file shopping-list.component.ts, tambahkan method untuk handling event penambahan ingredient dari shopping-edit.component.

import { Component, OnInit } from '@angular/core';
//import ingredient model
import { Ingredient } from '../shared/ingredient.model';

@Component({
  selector: 'app-shopping-list',
  templateUrl: './shopping-list.component.html',
  styleUrls: ['./shopping-list.component.css']
})
export class ShoppingListComponent implements OnInit {
  //menggunaan ingredient model
  ingredients : Ingredient[] = [
    new Ingredient("Oreo", 1),
    new Ingredient("Tepung", 1),
  ];

  constructor() { }

  ngOnInit(): void {
  }

  onIngredientAdded(ingredient : Ingredient){
    this.ingredients.push(ingredient);
  }

}

Karena kita bekerja dengan element form, pastikan FormsModule diimport melalui app.module.ts (lihat baris yang diberi comment).

import { NgModule} from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
//import formsmodule
import {FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { RecipesComponent } from './recipes/recipes.component';
import { RecipeListComponent } from './recipes/recipe-list/recipe-list.component';
import { RecipeDetailComponent } from './recipes/recipe-detail/recipe-detail.component';
import { RecipeItemComponent } from './recipes/recipe-list/recipe-item/recipe-item.component';
import { ShoppingListComponent } from './shopping-list/shopping-list.component';
import { ShoppingEditComponent } from './shopping-list/shopping-edit/shopping-edit.component';

@NgModule({
  declarations: [
    AppComponent,
    HeaderComponent,
    RecipesComponent,
    RecipeListComponent,
    RecipeDetailComponent,
    RecipeItemComponent,
    ShoppingListComponent,
    ShoppingEditComponent
  ],
  imports: [
    BrowserModule,
    FormsModule //import formsmodule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Sesuai ekspektasi, ingredient berhasil ditambahkan pada shopping-list.

Sharing is caring:

Leave a Comment