How to pass data from parent to child component in Angular 4

后端 未结 4 1776
一个人的身影
一个人的身影 2021-02-01 04:10

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

相关标签:
4条回答
  • 2021-02-01 04:45

    It can be done using Input()decorator. See below code -

    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 {{ childMessage}}
      `,
      styleUrls: ['./child.component.css']
    })
    export class ChildComponent {
    
      @Input() childMessage: string;
    
      constructor() { }
    
    }
    

    More Information

    0 讨论(0)
  • 2021-02-01 04:46

    With the help of Input() we can pass data

    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
    }
    
    0 讨论(0)
  • 2021-02-01 04:50

    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);
    }
    
    0 讨论(0)
  • 2021-02-01 04:53

    According to angular Lifecycle use the ngOnInit for initializing input values

    @Input() data;
    
    
    constructor() {
    }
    
    ngOnInit() {
      let question = this.data;
      console.log(this.question);
    }
    
    0 讨论(0)
提交回复
热议问题