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

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

NG构建后多余的国旗

如何在HTML外部项目中使用Web组件(以17角创建)

Change上的Angular 自定义控件无法正常工作

Angular 环境本地无文件替换

筛选器不会从文本输入触发更改事件

FromEvent不工作,本机事件绑定

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

如何让 ag-Grid 事件读取私有方法?

Angular 迁移 14 到 15 / 16:angular universal 是否停止将 <!-- this page was prerendered with angular universal --> 用于预渲染页面?

如何使用指令以Angular 传递默认值

无法将项目从 Angular 13 更新到 14

关闭 Dynamsoft Web Twain 弹出窗口

Subject.complete() 是否取消订阅所有听众?

如何修复 [Object: null prototype] { title: 'product' }

如何为 Angular 2 中的渲染元素绑定事件监听器?

angular4的所见即所得编辑器

Angular 2 中的 OnChanges 和 DoCheck 有什么区别?

安装特定版本的 ng cli

如何导航到同级路由?

从 Angular 中的自定义表单组件访问 FormControl