简体   繁体   English

如何在Angular4中将数据从子组件传递到父组件

[英]How to pass data from child component to parent component in Angular4

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... 我正在Angular4应用程序中工作。在此,我想将数据从子组件传递到父组件。让我解释一下详细信息...

app.component.html app.component.html

父组件图像

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 my-cart.component.html

子组件图像

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) 当我添加一些数量并单击“添加到购物车”按钮时,该数量将通过API传递到数据库以进行存储,并在此行中得到响应(数量)

.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 现在,我想从my-cart.component.html ..... app.component.html中显示数量计数。当数据存储在db中时,响应又回来了,我需要立即在父级中显示计数没有任何时间中断的组件

I have referred some examples in stackoverflow like chile to parent data passing but nothing is worked for me ... 我已经提到了stackoverflow中的一些示例,例如chile到父数据传递,但是对我没有任何帮助...

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..? Angular ..可以吗? yes ,means How can I achieve this ...? 是的,意味着我该如何实现...?

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. 我没有在您提供的HTML中看到购物车组件(我也看不到图像),但是如果您确实具有父子关系,则可以使用它来将数据从子项传递给父项。

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

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. 我最近还在为网站创建购物车,为此,我不是通过父服务和子组件之间传递数据,而是通过服务在组件之间传递数据.i通过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);
    }

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. 我已经使用RxJS的行为主题使用共享服务在stackblitz中完成了一个示例应用程序

All the components can access and change the same instance of message. 所有组件都可以访问和更改相同的消息实例。

read through this link to know more about BehaviorSubject . 阅读此链接以了解有关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)
  }

}
  1. Pass data from parent to child with input binding. 使用输入绑定将数据从父级传递到子级。 @Input()/@Input(AliasName). @Input()/ @ Input(别名)。 Example, @Input() hero: Hero; 例如, @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. 子组件公开一个EventEmitter属性,当发生某些事件时,该属性将发出事件。 The parent binds to that event property and reacts to those events. 父级绑定到该事件属性并对这些事件做出反应。 Example, 例,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM