有没有办法将对象传递给子女组件? (角)

发布于 2025-02-07 16:54:43 字数 2485 浏览 0 评论 0原文

每当单击它时,我都会创建一个按钮,它将所有值传递给此空对象“产品”。我正在尝试将此对象发射到子组件上,因此我可以将其推入产品中的空数组中。

    import { Component, Input } from '@angular/core';
    import { Item } from 'src/app/Model/Item';
    import { EventEmitter } from '@angular/core';
    @Component({
      selector: 'app-item',
      templateUrl: './item.component.html',
      styleUrls: ['./item.component.css']
    })
    export class ItemComponent  {
      items: Item[] = []
      @Input() addProduct: EventEmitter<Item> = new EventEmitter
      constructor(private storeService: StoreService) {
        this.items = this.storeService.getItem()
      }
addProducts(item: Item) {
    const product = {
      id: item.id,
      img: item.img,
      name: item.name,
      type: item.type,
      price: item.price,
      available: item.available
    }
    console.log(product)
    this.addProduct.emit(product)
    }
    }

- - (组件的模板)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <section>
        <div class="products">
        <ul *ngFor="let item of items">
                <img [routerLink]="['/product', item.id]" src = {{item.img}} alt="store pictures"/>
                <li >{{item.name}}</li>
                <li>{{item.type}}</li>
                <li>{{item.available}}</li>
                <li>{{item.price}}</li>
                <button (click)="addProducts(item)">Add to Cart</button>
            </ul>
        </div>
    </section>
</body>
</html>

-

//另一个组件(儿童)

import { Component, OnInit } from '@angular/core';
import { Item } from 'src/app/Model/Item';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {
  product: Item[] = []
  ngOnInit(): void {
  }

addProduct(post: Item){
this.product.push(post)
}
}

- 这是我在孩子模板中所做的。

<app-cart (addProduct)="addProduct($event)"></app-cart>

它给我一个错误,说“类型'事件'的参数不可分配给类型'item'的参数。 类型“事件”丢失了类型“项目”中的以下属性:ID,IMG,名称,价格,availablengtsc(2345)”

I've created a button whenever I click on it, it passes all values to this empty object 'product'. I'm trying to emit this object to the child component, so I can push it inside of the product empty array.

    import { Component, Input } from '@angular/core';
    import { Item } from 'src/app/Model/Item';
    import { EventEmitter } from '@angular/core';
    @Component({
      selector: 'app-item',
      templateUrl: './item.component.html',
      styleUrls: ['./item.component.css']
    })
    export class ItemComponent  {
      items: Item[] = []
      @Input() addProduct: EventEmitter<Item> = new EventEmitter
      constructor(private storeService: StoreService) {
        this.items = this.storeService.getItem()
      }
addProducts(item: Item) {
    const product = {
      id: item.id,
      img: item.img,
      name: item.name,
      type: item.type,
      price: item.price,
      available: item.available
    }
    console.log(product)
    this.addProduct.emit(product)
    }
    }

--
(template of the component)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <section>
        <div class="products">
        <ul *ngFor="let item of items">
                <img [routerLink]="['/product', item.id]" src = {{item.img}} alt="store pictures"/>
                <li >{{item.name}}</li>
                <li>{{item.type}}</li>
                <li>{{item.available}}</li>
                <li>{{item.price}}</li>
                <button (click)="addProducts(item)">Add to Cart</button>
            </ul>
        </div>
    </section>
</body>
</html>

--

// another component (child)

import { Component, OnInit } from '@angular/core';
import { Item } from 'src/app/Model/Item';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit {
  product: Item[] = []
  ngOnInit(): void {
  }

addProduct(post: Item){
this.product.push(post)
}
}

--
Here is what I did in the child template.

<app-cart (addProduct)="addProduct($event)"></app-cart>

It give me an error saying, "Argument of type 'Event' is not assignable to parameter of type 'Item'.
Type 'Event' is missing the following properties from type 'Item': id, img, name, price, availablengtsc(2345)"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

慢慢从新开始 2025-02-14 16:54:43

如果您想了解角度的​​工作方式,我建议按照 angular教程

但这是一个简单的示例,说明如何在组件之间进行交流。

项目列表组件

@Component({
  selector: 'app-items-list',
  templateUrl: './app-items-list.component.html',
  styleUrls: ['./app-items-list.component.css']
})
export class ItemsListComponent {
  @Input() items: Item[] = [];
  @Output() addProduct = new EventEmitter<Item>();

  addProducts(item: Item) {
    this.addProduct.emit(item);
  }
}

您无需在主HTML文件之外添加初始HTML

<div class="products">
  <ul *ngFor="let item of items">
    <img [routerLink]="['/product', item.id]" [src]="item.img" alt="store pictures" />
    <li>{{ item.name }}</li>
    <li>{{ item.type }}</li>
    <li>{{ item.available }}</li>
    <li>{{ item.price }}</li>
    <button (click)="addProducts(item)">Add to Cart</button>
  </ul>
</div>

标记

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent {
  @Input() products: Item[] = [];

  addProduct(product: Item) {
    this.products.push(product);
  }
}

。业务逻辑)

@Component({
  selector: 'app-root',
  template: `
    <app-items-list [items]="items" (addProduct)="addProduct($event)"></app-items-list>

    <app-card [products]="cartProducts"></app-card>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  readonly items = this.storeService.getItems();

  cartProducts: Item[] = [];

  constructor(private storeService: StoreService) {}

  addProduct(product: Item) {
    this.cartProducts.push(product);
  }
}

您的项目列表和购物车组件是愚蠢的组件,这意味着他们不知道数据的来源,并且应该保持这种状态(愚蠢的组件也是可重复使用的组件)。那就是父组件的作用。

父母正在通过服务获取数据,并将其传递给项目列表通过输入组件。
当单击添加产品按钮并将结果发送给父母时,项目列表组件会发出事件。
父母有责任将所选产品分配给购物车组件。

If you want to understand how things work in Angular, I suggest following the Angular tutorial.

But here's a simple example of how you can communicate between components.

Items List Component

@Component({
  selector: 'app-items-list',
  templateUrl: './app-items-list.component.html',
  styleUrls: ['./app-items-list.component.css']
})
export class ItemsListComponent {
  @Input() items: Item[] = [];
  @Output() addProduct = new EventEmitter<Item>();

  addProducts(item: Item) {
    this.addProduct.emit(item);
  }
}

You don't need to add the initial HTML markup outside of the main HTML file which is index.html

<div class="products">
  <ul *ngFor="let item of items">
    <img [routerLink]="['/product', item.id]" [src]="item.img" alt="store pictures" />
    <li>{{ item.name }}</li>
    <li>{{ item.type }}</li>
    <li>{{ item.available }}</li>
    <li>{{ item.price }}</li>
    <button (click)="addProducts(item)">Add to Cart</button>
  </ul>
</div>

Cart Component

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent {
  @Input() products: Item[] = [];

  addProduct(product: Item) {
    this.products.push(product);
  }
}

Parent Component (responsible for handling the business logic)

@Component({
  selector: 'app-root',
  template: `
    <app-items-list [items]="items" (addProduct)="addProduct($event)"></app-items-list>

    <app-card [products]="cartProducts"></app-card>
  `,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  readonly items = this.storeService.getItems();

  cartProducts: Item[] = [];

  constructor(private storeService: StoreService) {}

  addProduct(product: Item) {
    this.cartProducts.push(product);
  }
}

Your items list and cart components are dumb components, meaning they don't know where the data is coming from and they should stay that way (the dumb components are also reusable components). That is the role of the parent component.

The parent is fetching the data through a service and passes it to the items list component through an input.
The items list component emits an event when the Add Product button is clicked and sends the result to the parent.
The parent is responsible to distribute the selected products to the cart component.

鹿港巷口少年归 2025-02-14 16:54:43

最通用的交叉组件解决方案是使用主题。首先创建将用于通信的服务(ng g服务foo)。然后在服务上创建新主题:

addProductsub = new主题;

将此新服务导入父和子组件。要发射,只需致电您的主题的下一个方法,并将其作为参数发送您要发送的内容:

this.importedservice.addproductsub.next(product)

在儿童组件上,订阅主题并描述收到新数据时该做什么。

this.importedservice.addproductsub.subscribe(((data)=&gt; {
this.productEmptyArray = data; })

为了防止内存泄漏分配摘要(子组件)到变量,并调用.unsubscribe()

The most universal cross component solution is to use Subject. First create a service that will be used for communication (ng g service foo). Then create new subject on the service:

addProductSub = new Subject;

Import this new service to parent and to child component. To emit, just call next method on your subject and pass as argument what ever you wish to send:

this.importedService.addProductSub.next(product)

On child component, subscribe to subject and describe what to do when new data is received.

this.importedService.addProductSub.subscribe((data) => {
this.productEmptyArray = data; })

To prevent memory leakage assign subsciption (child component) to a variable and call .unsubscribe() in ngOnDestroy lifecycle hook

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文