[英]Angular 6: use the value of an @Input within an ngOnInit
I'd like to retrieve the value of the model car by using an input, but I'm not sure of how it works. 我想通过使用输入来检索模型车的价值,但是我不确定它是如何工作的。 Here's what I've tried.
这是我尝试过的。
@Input() model : Car
car: Car;
ngOnInit() {
this.car= this.carService.getcar(model.id);
}
Unfortunetaly model is always empty.How can I do? 不幸的模型总是空的,我该怎么办?
EDIT: Parent HTML 编辑:父HTML
<app-model
[model]="car">
</app-model>
PARENT ts file 家长ts文件
ngOnInit{
this.shopService.get()
.pipe(
take(1),
finalize(() => {
})
)
.subscribe(result => {
this.car = result;
});
})
)
}
您必须使用@Input()
(带有方括号)
In HTML of another component 在另一个组件的HTML中
<app-detail-component [model]="{id: 1, name: 'Carname'}"></app-detail-component>
In the .ts file of your described component (I assumed the name of the Component is DetailComponent.ts) 在您描述的组件的.ts文件中(我假设该组件的名称为DetailComponent.ts)
@Input() model: Car;
car: Car;
ngOnInit() {
this.car= this.carService.getcar(model.id);
}
Link to official documentation: https://angular.io/guide/component-interaction 链接到官方文档: https : //angular.io/guide/component-interaction
model
is empty because variable car
in parent component is assigned after ngOnInit
is invoked in the child component. model
为空,因为在子组件中调用ngOnInit
之后,在父组件中分配了可变car
。 You need to call a method of carService
in ngOnChanges
, not ngOnInit
. 您需要在
ngOnChanges
中而不是ngOnInit
调用carService
方法。
@Input() model: Car
car: Car;
ngOnChanges() {
this.car = this.carService.getcar(model.id);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.