角度值来到子组件模板,但在ngOnInit中未定义

时间:2018-02-01 07:07:17

标签: angular angular-components ngoninit

当我将值传递给模板中的子组件值但未在子组件的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;
        }
    );
  }
}

1 个答案:

答案 0 :(得分: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