0

When I pass the value to child component values coming in template but not showing in ngOnInit of child component

parent Component

<div class="overview bg-blue-pattern">prospectId {{prospectId}}
        <app-calls-log-history [prospectid]="prospectId"></app-calls-log-history>
    </div>

Child Componnet

<div class="calls-log-history-container">
        prospectId {{prospectid}}
    </div>

Child component ts file

import { Component, OnInit,Input } from '@angular/core';
import { ContactFilterService } from '../../../../services/contact.service';

@Component({
  selector: 'app-calls-log-history',
  templateUrl: './calls-log-history.component.html',
  styleUrls: ['./calls-log-history.component.scss']
})
export class CallsLogHistoryComponent implements OnInit {
  @Input() prospectid: any;
  CallsLogHistory: Array<any> = [];
  constructor( private _contactFilterService: ContactFilterService) { }
  ngOnInit() {
    console.log('prospectid : '+ this.prospectid); // coming as undefined
    this._contactFilterService.getCallsLogHistory(this.prospectid).subscribe(
        result => {
            this.CallsLogHistory = result.notes;
        }
    );
  }
}
Mohammad Fareed
  • 1,927
  • 6
  • 26
  • 59
  • https://stackoverflow.com/questions/41389124/angular-2-how-to-make-child-component-wait-for-asyn-data-to-be-ready/41389243#41389243 – Jecfish Feb 01 '18 at 07:13

1 Answers1

2

short answer, using *ngIf

<div class="overview bg-blue-pattern" *ngIf="prospectId">prospectId {{prospectId}}
    <app-calls-log-history [prospectid]="prospectId"></app-calls-log-history>
</div>

long answer, this happen because your prospectId is initially nothing until you called an async method and bind it. Child component already init one time when the prospectId is nothing.

Refer to this post for details: https://scotch.io/tutorials/3-ways-to-pass-async-data-to-angular-2-child-components#toc-solution-3-use-rxjs-behaviorsubject

Jecfish
  • 4,026
  • 1
  • 18
  • 16