【问题标题】:Unable to access Input Property in NgOnInit -Angular 6无法访问 NgOnInit -Angular 6 中的输入属性
【发布时间】:2026-01-11 08:40:01
【问题描述】:

我的父页面如下所示。

html:

<counter  [conversationId]="conversationId"></counter>

组件:

public conversationId: string;

public showModal() {   
 this.conversationId = '1234'
 this.modalService.showComponent(CounterPage, { class: 'modal-lg' }); 
}

我的孩子页面如下所示。

 @Input() conversationId: any;
 public ngOnInit  (): void {
    alert(this.conversationId); //shows undefinded.
  }

看起来这是常见问题here。没有一个解决方案对我有用。

【问题讨论】:

  • 传入时conversationId是什么?如果您传入undefined,那么它仍然是undefined 是有道理的。
  • 我没有通过 undefined。我的代码清楚地显示在调用 show 组件之前将“1234”分配给 conversationId

标签: angular


【解决方案1】:

参数在方法 ngAfterContentInit() 之前接收值。

在这张图片中查看 Angular 的生命周期:https://v2.angular.io/resources/images/devguide/lifecycle-hooks/hooks-in-sequence.png

尝试:

@Input() conversationId: any;
 public ngAfterContentInit  (): void {
    alert(this.conversationId); //shows undefinded.
  }

【讨论】:

  • 那么,访问 conversationId 的最佳方式是什么?
  • 我知道的最好的方法是使用 ngAfterContentInit 或构造函数,但是我更喜欢使用 ngAfterContentInit
  • 值未显示在 nfAfterContentInit 中,您的代码 cmets 显示未定义