我想将对象传递给子组件。我什么都做了,什么都没做。(角度)
这是父组件:我将所有数据从父组件传递到主页组件。
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);
}
}
(模板)您可以注意到有一个单击按钮,在该按钮中我将此方法发送给父组件,因此我可以将其值传递给另一个子组件。
<!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 中使用任何值,为什么?