This is the parent component: I passed all the data from the parentComponent to main-page Component.

import { Component, OnInit } from '@angular/core';
import { Product } from '../Model/Product';
import { ProductService } from '../ProductsService/product.service';

@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.css'],
})
export class ParentComponent implements OnInit {
    products: Product[] = [];
    cartList: Product[] = [];
    constructor(private productService: ProductService) {
        this.products = this.productService.getProducts();
    }

    ngOnInit(): void {}

    addCart(product: Product) {
        this.cartList.push(product);
    }
}

(TEMPLATE)

<app-main-page [products]="products" (addCart)="addCart($event)"></app-main-page>
<app-cart-list [cartList]="cartList"></app-cart-list>
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { ProductService } from '../../ProductsService/product.service';
import { Product } from '../../Model/Product';

@Component({
    selector: 'app-main-page',
    templateUrl: './main-page.component.html',
    styleUrls: ['./main-page.component.css'],
})
export class MainPageComponent {
    @Input() products: Product[] = [];
    @Output() addCart: EventEmitter<Product> = new EventEmitter();
    constructor(private productService: ProductService) {
        this.products = this.productService.getProducts();
    }

    addToCartList(product: Product) {
        this.addCart.emit(product);
        console.log(product);
    }
}

(TEMPLATE) As you can notice that there's a click button in which I emitted this method to the parent so I can pass its value to another child 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 product of products">
                    <img src="{{ product.img }}" alt="store pictures" />
                    <li>{{ product.name }}</li>
                    <li>{{ product.type }}</li>
                    <li>{{ product.available }}</li>
                    <li>{{ product.price }}</li>
                    <button (click)="addToCartList(product)">Add to Cart</button>
                </ul>
            </div>
        </section>
    </body>
</html>
import { Component, Input, OnInit } from '@angular/core';
import { Product } from 'src/app/Model/Product';
@Component({
    selector: 'app-cart-list',
    templateUrl: './cart-list.component.html',
    styleUrls: ['./cart-list.component.css'],
})
export class CartListComponent implements OnInit {
    constructor() {
        console.log(this.cartList);
    }
    @Input() cartList: Product[] = [];
    ngOnInit(): void {}
}

I cannot use any value in cartList, why?

推荐答案

Input variables, event emitters, and RxJS just complicate the problem here. All you need is a simple Angular service.

Here is a stackblitz: https://stackblitz.com/edit/angular-ivy-a6ub1h?file=src/app/app.component.html


Your parent component doesn't need any typescript, all it needs to do is instantiate the other components via html:

Parent Component

<app-main-page></app-main-page>
<app-cart-list></app-cart-list>

I'll make a product service to simulate your app, although I'm not sure exactly what your service looks like. Products will just have a name for simplicity.

Product Service

export type Product = {
  name: string;
};

@Injectable({ providedIn: 'root' })
export class ProductService {
  getProducts(): Product[] {
    return [
      { name: 'product1' },
      { name: 'product2' },
      { name: 'product3' },
      { name: 'product4' },
      { name: 'product5' },
      { name: 'product6' },
      { name: 'product7' },
      { name: 'product8' },
    ];
  }
}

And I'll make a service to hold the cart list items, we'll have add and delete functionality.

Cart Service

@Injectable({ providedIn: 'root' })
export class CartService {
  cartList: Product[] = [];

  addToCart(product: Product) {
    this.cartList.push(product);
  }

  deleteFromCart(index: number) {
    this.cartList.splice(index, 1);
  }
}

Main page just gets the products and can add them to the cart.

Main Page

export class MainPageComponent implements OnInit {
  products: Product[] = [];

  constructor(
    private prodService: ProductService,
    private cartService: CartService
  ) {}

  ngOnInit() {
    this.products = this.prodService.getProducts();
  }

  addToCart(product: Product) {
    this.cartService.addToCart(product);
  }
}
<h1>Main Page</h1>
<ng-container *ngFor="let product of products">
  <span>{{ product.name }}&nbsp;</span>
  <button (click)="addToCart(product)">Add to Cart</button>
  <br />
</ng-container>

Cart component shows the cart items and can delete them

Cart List

export class CartListComponent {
  constructor(private cartService: CartService) {}

  get cartList() {
    return this.cartService.cartList;
  }

  delete(index: number) {
    this.cartService.deleteFromCart(index);
  }
}
<h1>Cart</h1>
<ng-container *ngFor="let product of cartList; index as i">
  <span>{{ product.name }}&nbsp;</span>
  <button (click)="delete(i)">Delete</button>
  <br />
</ng-container>

Angular相关问答推荐

Angular material 输入字段中的图标未显示

Angulat 17@ngrx/Signals或全球服务,用什么?

Angular :仅当 Select 第一个日期时才显示第二个日期字段

使Angular 效果只执行一次

如何在投影项目组周围添加包装元素?

笔刷Angular 为17

NGNEW不会在src根文件夹ANGLI CLI 17.0.10中生成app.mode.ts

Angular 17:在MouseOver事件上 Select 子组件的正确ElementRef

[NullInjectorError]:R3InjectorError(Standalone[_AppComponent])[]:NullInjectorError:No provider for _HttpClient

如何使用独立组件在ANGLE(16+)中实现嵌套布线

在Cypress中,对xlsx文件的读取并不总是正确的

Angular 16 Auth Guard在具有0的服务时给出Null Injector错误;httpclient;被注入

当快速拖动光标时会丢失元素 - Angular

Angular:为什么在我的自定义 ErrorHandler 中订阅主题不触发?

使用 RxJS forkJoin 时传递参数的最佳方式

带有嵌套表单数组的 Angular react式表单

如何将服务变量传递到 Angular Material 对话框?

如何从组件模板将数组作为 Input() 传递?

Firestore 从集合中获取文档 ID

Firebase 查询子项的子项是否包含值