0

I am working in an Angular4 application.In this I want to pass data from child component to parent component.let me explain the details...

app.component.html

parent component image

code...

 <div class="col-3">
          <br>
          <form class="form-inline">
            <div class="input-group">
              <div class="input-group-prepend">
                <span class="input-group-text" id="basic-addon1">
                    <i class="fas fa-shopping-bag text-primary" style="font-size:40px"></i>
                </span>
              </div>
              <input type="text" class="form-control bg-white"  placeholder="My Cart" value="  My Cart  {{totalcartval}} Item(s)" readonly >  
            
            </div>
          </form>
        </div>

my-cart.component.html

child component image

code...

 import { Component,EventEmitter,Output } from '@angular/core';
    import { Router } from '@angular/router';
    import { HttpClient } from '@angular/common/http';
    import { SessionStorageService,SessionStorage } from 'angular-web-storage';
    
    
    @Component({
      selector: 'app-my-cart',
      templateUrl: './my-cart.component.html',
      styleUrls: ['./my-cart.component.css'],
      outputs :['ChildEvent']
    })
    
    export class MyCartComponent  {

    public sendRecord(Totalcartval : number ) {  
          this.http.get('http://freegeoip.net/json/?callback')
                     .subscribe(
                        data => this.saveIP(data['ip'],Totalcartval),
                        error => console.error(error)
                     );
        }
        saveIP(address: string,cartval :number) {
          this.http.get(`http://localhost:57036/api/data/CartCount/?IP_ADDRESS=${address}&ITEM_QTY=${cartval}&TIME=${this.fixedTimezone}`)
                   .subscribe(data => this.res = data['ITEM_QTY']);
      }  
    ngOnInit() {}
    }

When I added some quantity and clicked on the "Add to Cart " button the quantity is passed to the database for storing through the API and got the response in this line (quantity in number)

.subscribe(data => this.res = data['ITEM_QTY']);

Now I want to display the quantity count to the app.component.html from the my-cart.component.html ....when the data is stored in db the response is came back and immediately I need to show the count in parent component without any time break

I have referred some examples in stackoverflow like chile to parent data passing but nothing is worked for me ...

some examples like child to parent data passing ,need to display the child component in parent component but in my case I don't want to display the child in parent ,why because if I have added some product in my cart I could be able to navigate back to my parent component and further add other products in my cart...

Is it possible with Angular..? yes ,means How can I achieve this ...?

Community
  • 1
  • 1
Nikson
  • 900
  • 2
  • 21
  • 51
  • you can use the state management technique to achieve this refer this [**repository**](https://github.com/aravindfz/angular-2-basic-spa) – Aravind Mar 16 '18 at 09:43

4 Answers4

0

I don't see your cart component into the HTML you provided (and I can't see the images), but if you really have a parent-child relation, then you can use this to pass data from the child to the parent.

In the child

constructor(@Host() parent: ParentComponent) {}

Now, you can use whatever you want to pass the data.

For instance

this.parent['bridge'] = data; // If you don't want to declare a variable in the parent
this.parent.doSomething(); // Calling a function i the parent
this.parent.myVar = data; // If you have declared a variable in the parent
0

I was also working on creating a cart for a website recently.For this, instead of passing data between parent and child component, i was passing the data between components through a service.i was storing the product in the cart through Form.

For the view:

<div class="products" *ngFor= "let product of Object.values(getItemsFromCartService()) ">
        <div class="product">
          <img [src]="product['imgURL']" [alt]="product.productSelected">
          <h4>{{product.productSelected}}</h4>
        </div>
        <div class="quantity">
          Qty.
            <input #qty (blur)="updateQuantity(product, qty.value)" type="number" name="Quantity" [value]="product.Quantity" class="form-control">
        </div>
        <span class="glyphicon glyphicon-trash" (click)="removeItem(product.productSelected)"></span>
        <div class="productQtnPrice">
              <h4 class="totalPrice"><i class="fa fa-inr"></i> {{product.totalPrice}} </h4>
        </div>
    </div>

I have used the blur event to update the quantity of the product. You can use bind the same method to your's + and -.

In the typescript:

getItemsFromCartService() {
    this.totalItemsInCart = this._cartService.getAllItems();
    this.setItemDetails();
    console.log(this.totalItemsInCart);
    return this.totalItemsInCart;
}

updateQuantity(product, newQuantity) {
        console.log("Updating quantity");
        this._cartService.updateQuantity(product, newQuantity);
    }
removeItem(productName) {
        this._cartService.removeItem(productName);
    }
Shadab Faiz
  • 2,380
  • 1
  • 18
  • 28
0

Use shared service to share data between components without any relationships. Please read this link for more information. I have done a sample app in stackblitz with shared service using behavior subject from RxJS.

All the components can access and change the same instance of message.

read through this link to know more about BehaviorSubject.

Shared Service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject<string>("default message");
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}
Prithivi Raj
  • 2,658
  • 1
  • 19
  • 34
0
  1. Pass data from parent to child with input binding. @Input()/@Input(AliasName). Example, @Input() hero: Hero;

  2. Intercept input property changes with a setter. Use an input property setter to intercept and act upon a value from the parent. Example,

    @Input() set name(name1: string) { this._name = (name1 && name1.trim()) || '<no name set>’; }

    Example,

    @Input() set age(ageNum: number) { this._age = (ageNum) || '<no age set>’; }

    <app-name-child *ngFor="let personName of names" [name]=“personName“ [age]=“personage”></app-name-child>

  3. Parent listens for child event. The child component exposes an EventEmitter property with which it emits events when something happens. The parent binds to that event property and reacts to those events. Example,

    @Output() voted = new EventEmitter<boolean>();
    (voted)="onVoted($event)"

TheSprinter
  • 1,523
  • 17
  • 30