【问题标题】:Use @Input in ngOnInit在 ngOnInit 中使用 @Input
【发布时间】:2018-08-21 09:42:21
【问题描述】:

我已使用@Input 将应用程序object 从父组件传递到子组件。现在我试图在子组件的ngOnInit 上使用它。该对象仅在ngOnChanges 上可用,因此无法在ngOnInit 上使用。我仍然尝试了以下类似的方法,但无法使其正常工作。

组件

@Input() app;
appModified;

listDetails() {
    this.appService.getDetails(this.appModified);
}

ngOnChanges() {
    console.log(this.app)
    this.appModified = this.app;
}

ngOnInit() {
    this.listDetails();
}

listDetails 是undefined

我尝试了this approach,但仍然无法修复它。

感谢任何帮助。谢谢

【问题讨论】:

  • ngAfterViewInit()中调用this.listDetails();
  • @Faisal 我也试过了,但没用
  • ngOnInit() { setTimeout(()=>{ this.listDetails(); },0) }
  • 您知道 ngOnChanges 可以多次调用吗?
  • 如果你在父组件中检查你的输入数据,那么它会在数据满时填充数据,<child *ngIf="objects" [app]="objects"></child>这是什么问题?

标签: angular


【解决方案1】:

@surazzarus

确保您的 html 模板与下面类似,其中 someString 内容将实例绑定到子级的 name 属性:

<hello [name]="someString"></hello>

someString 变量在我的 app.component 中声明如下:

someString: string = '123 123 123';

最后一段代码:

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

@Component({
  selector: 'hello',
  template: `<span>{{name}}</span>`
})
export class HelloComponent  {
  @Input() name: string;

  ngOnInit() {
    console.log(this.name);
}

  ngOnChanges() {
    console.log(this.name)
}
}

希望对你有帮助

检查整个样本here

【讨论】:

    猜你喜欢
    • 2019-07-08
    • 2019-11-27
    • 2018-06-22
    • 2018-07-26
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 2017-10-18
    • 1970-01-01
    相关资源
    最近更新 更多