Advertisement
randomCodes

ng4 - task 02

Aug 16th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //In my code, newItem is only local, i don't see any reason to expose it outside the class.
  2.  
  3. //Sorry for long file names, i used ng g c CartComponent  :/
  4.  
  5. //cart-component.component.ts
  6. import { Component, Input, Output, EventEmitter } from '@angular/core';
  7. @Component({
  8.  selector: 'app-cart-component',
  9.  templateUrl: './cart-component.component.html',
  10.  styleUrls: ['./cart-component.component.css']
  11. })
  12. export class CartComponentComponent {
  13.  @Input() items: Array<string>;
  14.  @Output() addItem = new EventEmitter<string>();
  15.  newItem: string;
  16.  onNewItem(event) {
  17.  this.newItem = event.target.value;
  18.  }
  19.  onAddNewItem() {
  20.  this.addItem.emit(this.newItem);
  21.  }
  22. }
  23.  
  24. //cart-component.component.html
  25. <div>
  26.  <h1>Shopping Cart</h1>
  27.  New Item: <input type="text" (input)="onNewItem($event)" />
  28.  <button (click)="onAddNewItem($event)">Add Item</button>
  29. </div>
  30.  
  31. //app.component.html
  32. <app-cart-component [items]="initialArray" (addItem)="onItemAdded($event)"></app-cart-component>
  33.  
  34. //app.component.ts
  35. ...
  36. export class AppComponent {
  37.  initialArray = ['Apples', 'Bananas', 'Cherries'];
  38. onItemAdded(newItem) {
  39.  this.initialArray.push(newItem);
  40.  console.log(this.initialArray);
  41.  }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement