Home > front end >  How to do a *ngFor using a property passed by the parent component?
How to do a *ngFor using a property passed by the parent component?

Time:12-11

I'm trying to pass a "jobs" property to my child component, this property is an array with two objects.

When I try to do *ngFor on it via "@Input" it does nothing.

When I do a console.log in the code I get: "[object Object],[object Object]"

I tried passing the "jobs" property from the parent component to the child and using *ngFor on it to generate a dynamic list.

I expected my table to be populated with the array list.

<div>
   <table-list jobs={{jobs}}></table-list>
</div>


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

@Component({
  selector: 'home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit{

@Input() jobs = [
  {
    "name": "Wipro",
    "start": "01/08/2021",
    "finish": "At Moment"
  },
  {
    "name": "Lynk",
    "start": "01/03/2021",
    "finish": "01/08/2021"
  }
]

ngOnInit(): void {
  
}

}




<div>
    <tbody>
        <tr *ngFor="let job of jobs; index as i; first as isFirst">
            <td>{{job.name}}</td>
            <td>{{job.start}}</td>
            <td>{{job.finish}}</td>
        </tr>
    </tbody>
</div>





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

@Component({
  selector: 'table-list',
  templateUrl: './table-list.component.html',
  styleUrls: ['./table-list.component.scss']
})
export class TableListComponent implements OnInit {

  @Input() jobs: any;

  ngOnInit(): void {
    console.log("jobs", this.jobs)
  }
}

CodePudding user response:

use property binding to pass value to the child component like below

<div>
   <table-list [jobs]="jobs"></table-list>
</div>

Stackblitz

  • Related