/**/

这是父组件:我将所有数据从父组件传递到主页组件.

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);
    }
}

(模板)

<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);
    }
}

(模板) 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 {}
}

我无法使用cartList中的任何值,为什么?

推荐答案

输入变量、事件emits 器和RXJ只会使问题复杂化.你所需要的只是一个简单的Angular 服务.

这里有一个stackblitz:https://stackblitz.com/edit/angular-ivy-a6ub1h?file=src/app/app.component.html


父组件不需要任何typescript,只需通过html实例化其他组件:

Parent Component

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

我将制作一个产品服务来模拟你的应用程序,尽管我不确定你的服务到底是什么样子.产品只会有一个简单的名字.

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' },
    ];
  }
}

我会做一个服务来保存购物车列表中的物品,我们会有添加和删除功能.

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

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 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相关问答推荐

Renderer2.appendChild 没有按预期工作?

Angular 从 13.3.8 恢复到 13.3.7

react表单上的自定义验证器用于密码并确认密码匹配将未定义的参数导入 Angular 4

可从 Angular2 中的

无法获得 angular-material md-sidenav 的 100% 高度

Angular2订阅对子组件中@Input的更改

如何在 Angular CLI 1.1.1 版中将路由模块添加到现有模块?

在 Angular rxjs 中,我什么时候应该使用 `pipe` 与 `map`

在Angular2中获取服务的域名

如何从 EventEmitter 函数返回值?

获取对组件中使用的指令的引用

@Input 属性在 Angular 2 的 onInit 中未定义

为什么 colspan 在 Angular 2 中不是已知的原生属性?

Angular 2如果路径不存在,如何重定向到404或其他路径

使用Angular 2 中的按钮导航到另一个页面

迭代Angular中的对象

Angular ngModule 中的 entryComponents 是什么?

*ngIf else if 在模板中

Angular 2 http.post() 没有发送请求

如何返回上一页