如何在Angular 4中将数据从父组件传递到子组件 [英] How to pass data from parent to child component in Angular 4

查看:76
本文介绍了如何在Angular 4中将数据从父组件传递到子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试将数据从父组件传递到子组件时.我在控制台中收到未定义的消息.数据采用数组形式.

When I try to pass data from parent to child component. I'm getting undefined message in the console. Data is in the form of array.

parent.component.html

<div class="section welcome-section fp-section fp-table" *ngFor="let section of sections">
    <div class="fp-tableCell">
      <app-question-card [data]="section"></app-question-card>
    </div>
  </div>

child.component.ts

@Input() data;
  question = [];
  constructor() {
    this.question = this.data;
  }

  ngOnInit() {
    console.log(this.question); //returns undefined
  }

推荐答案

您不能在构造函数中进行赋值,因为尚未填充该值,应仅在 ngOnInit 中完成就像您检查的值一样.

You can't do the assignment in the constructor as the value has not yet been populated, it should be done in ngOnInit just like your check of the value.

@Input() data;
question = [];

constructor() {
}

ngOnInit() {
  this.question = this.data;
  console.log(this.question);
}

这篇关于如何在Angular 4中将数据从父组件传递到子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆