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

Angular 5:子组件向父组件传递数组并在父组件展示的方法

解决子组件数组传递给父组件并展示的问题

嘿,你这里搞反数据传递方向啦!@Input()是用来父组件往子组件传数据的,要把子组件的数组传给父组件,咱们得用@Output()配合EventEmitter来实现,下面一步步教你改:

1. 修改子组件代码

首先把原来的@Input()去掉,换成@Output()和EventEmitter,在ngOnInit里把数组发射给父组件:

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child', // 这里换成你实际的子组件selector,比如你原来的<app.parent>应该是笔误,改成正确的标签名
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  // 定义一个事件发射器,用来向父组件传递数据
  @Output() dataEmitter = new EventEmitter<string[]>();

  ngOnInit() {
    const childData = ['name1', 'name2', 'name3'];
    // 把数组发射给父组件
    this.dataEmitter.emit(childData);
  }
}

2. 修改父组件代码

父组件需要定义一个变量接收数据,再通过模板监听子组件的事件拿到数据,最后渲染展示:

父组件TS文件

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  // 用来存储子组件传递过来的数组
  parentData: string[] = [];

  // 接收子组件数据的方法,$event就是子组件发射的数组
  receiveChildData(data: string[]) {
    this.parentData = data;
  }
}

父组件模板文件

<!-- 监听子组件的dataEmitter事件,调用receiveChildData接收数据 -->
<app-child (dataEmitter)="receiveChildData($event)"></app-child>

<!-- 渲染展示子组件传递过来的数组 -->
<h3>子组件传递的数组内容:</h3>
<ul>
  <!-- 用*ngFor循环遍历数组,展示每一项 -->
  <li *ngFor="let item of parentData">{{ item }}</li>
</ul>

补充说明

  • $event是Angular事件绑定里的特殊变量,代表子组件通过emit()发送过来的数据,这里就是我们的字符串数组。
  • 确保子组件的selector和父组件模板里使用的标签一致,比如子组件selector是app-child,父组件就用<app-child>标签。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:57:40