如何在Angular 4中将数据从父组件传递到子组件

时间:2017-07-19 11:34:02

标签: angular typescript

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

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
  }

4 个答案:

答案 0 :(得分:30)

您无法在构造函数中执行赋值,因为尚未填充值,应该在ngOnInit中完成,就像检查值一样。

@Input() data;
question = [];

constructor() {
}

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

答案 1 :(得分:2)

根据角度生命周期,请使用ngOnInit初始化输入值

@Input() data;


constructor() {
}

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

答案 2 :(得分:0)

可以使用Input()装饰器来完成。参见下面的代码-

  

parent.component.ts-

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

@Component({
  selector: 'app-parent',
  template: `
    <app-child [childMessage]="parentMessage"></app-child>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent{
  parentMessage = "message from parent"
  constructor() { }
}
  

child.component.ts-

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

@Component({
  selector: 'app-child',
  template: `
      Say {{ message }}
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent {

  @Input() childMessage: string;

  constructor() { }

}

更多Information

答案 3 :(得分:0)

借助Input(),我们可以传递数据

Child.html

<app-chart [userDetails]='<< JSON OBJ | ANY VALUE WHICH YOU WANT TO PASS >>'></app-chart>

chart.component.ts

@Input() userDetails: any = [];

ngOnInit() {
    console.log(this.userDetails); // as per angular Lifecycle use the ngOnInit for initializing input values
}