You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

同父组件下子组件数据传递:实现选中产品详情展示

解决Angular父子组件产品数据传递问题

嘿,我来帮你搞定这个产品详情展示的需求!既然你已经在父组件products.component里拿到了用户选中的产品,接下来只需要简单三步就能把数据传递给product-details.component并展示出来:

1. 给子组件定义输入属性

首先在ProductDetailsComponent中,通过@Input()装饰器声明一个用于接收父组件数据的属性。这样父组件就能把选中的产品传递进来了:

import { Component, Input } from '@angular/core';
// 记得导入你的Product数据类型(如果有定义接口的话)
import { Product } from '../path-to-your-product-model';

@Component({
  selector: 'app-product-details',
  templateUrl: './product-details.component.html',
  styleUrls: ['./product-details.component.css']
})
export class ProductDetailsComponent {
  // 定义输入属性,允许父组件传递选中的产品
  @Input() selectedProduct: Product | undefined;
}

2. 父组件模板绑定数据到子组件

打开products.component.html,找到你引入app-product-details的位置,把父组件中存储选中产品的变量(比如你已经拿到的那个变量,假设叫selectedProduct)绑定到子组件的selectedProduct输入属性上:

<!-- 父组件模板中的子组件标签 -->
<app-product-details [selectedProduct]="selectedProduct"></app-product-details>

3. 子组件模板展示产品详情

现在可以在product-details.component.html里用插值表达式展示产品数据了,记得加个*ngIf判断,避免初始没有选中产品时出现报错:

<div *ngIf="selectedProduct" class="product-details">
  <h3>{{ selectedProduct.name }}</h3>
  <p class="price">¥{{ selectedProduct.price }}</p>
  <p class="description">{{ selectedProduct.description }}</p>
  <!-- 根据你的产品字段添加更多展示内容 -->
</div>
<div *ngIf="!selectedProduct" class="empty-state">
  <p>请选择一个产品查看详情</p>
</div>

小提示

  • 确保你的Product接口(或类型)字段和实际产品数据的字段一致,避免展示时出现undefined;
  • 如果产品数据是异步获取的,也不用慌,Angular会自动在数据更新时同步更新子组件的展示内容。

内容的提问来源于stack exchange,提问作者yash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:01:55