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

如何将父组件Patient-prescription.components.ts中的对象传递给子组件?

Angular父组件向子组件传递对象的实现步骤

1. 子组件定义输入属性

在子组件Patient-prescription-expand-view.component.ts中,通过@Input()装饰器声明接收父组件数据的属性:

import { Component, Input } from '@angular/core';

// 先定义对象类型(可选但推荐,提升类型安全性)
interface Prescription {
  id: number;
  drugName: string;
  dosage: string;
  // 按需添加其他属性
}

@Component({
  selector: 'app-patient-prescription-expand-view',
  templateUrl: './patient-prescription-expand-view.component.html',
  styleUrls: ['./patient-prescription-expand-view.component.css']
})
export class PatientPrescriptionExpandViewComponent {
  // 声明输入属性,用于接收父组件传递的对象
  @Input() prescriptionData!: Prescription;
}

2. 父组件准备数据并绑定传递

在父组件Patient-prescription.components.ts中定义要传递的对象:

import { Component } from '@angular/core';
import { Prescription } from './patient-prescription-expand-view.component';

@Component({
  selector: 'app-patient-prescription',
  templateUrl: './patient-prescription.component.html',
  styleUrls: ['./patient-prescription.component.css']
})
export class PatientPrescriptionComponent {
  // 初始化要传递的对象数据
  currentPrescription: Prescription = {
    id: 1,
    drugName: '布洛芬',
    dosage: '每日2次,每次1片'
  };
}

然后在父组件的模板文件(patient-prescription.component.html)中,通过属性绑定将对象传递给子组件:

<app-patient-prescription-expand-view [prescriptionData]="currentPrescription"></app-patient-prescription-expand-view>

3. 子组件使用传递的对象

在子组件的模板文件(patient-prescription-expand-view.component.html)中直接使用接收的对象数据:

<div class="prescription-card">
  <h4>处方详情</h4>
  <p>处方ID:{{ prescriptionData.id }}</p>
  <p>药品名称:{{ prescriptionData.drugName }}</p>
  <p>服用剂量:{{ prescriptionData.dosage }}</p>
</div>

注意事项

  • 若对象可能为null或undefined,建议使用可选链操作符?.避免报错,例如{{ prescriptionData?.drugName }}
  • 如需监听对象变化,可在子组件中实现ngOnChanges生命周期钩子

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 18:40:17