0

当我将值传递给模板中的子组件值但未显示在子组件的 ngOnInit 中时

父组件

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

子组件

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

子组件ts文件

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;
        }
    );
  }
}
4

1 回答 1

2

简短的回答,使用*ngIf

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

长答案,这是因为在prospectId您调用异步方法并绑定它之前,您最初什么都不是。当什么都不是时,子组件已经init有一次了。prospectId

有关详细信息,请参阅此帖子:https ://scotch.io/tutorials/3-ways-to-pass-async-data-to-angular-2-child-components#toc-solution-3-use-rxjs-behaviorsubject

于 2018-02-01T07:17:05.053 回答