在ngOnInit中使用@Input

时间:2018-08-21 09:42:22

标签: angular

我已使用object将应用@Input从父组件传递到子组件。现在,我尝试在子组件的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,但仍然无法解决。

感谢您的帮助。谢谢

1 个答案:

答案 0 :(得分:-2)

@surazzarus

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

<hello [name]="someString"></hello>
在我的app.component中声明了

someString变量,如下所示:

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