Angular 如何在子组件中获取输入参数?

Angular 如何在子组件中获取输入参数?,angular,angular5,Angular,Angular5,在父组件中,我有: <app-access-password [profileId]="getProfileId(kid.getId())"></app-access-password> 我收到了未定义的消息。为什么?加载视图后需要访问,请将其移动到ngOnInit()方法 您必须在ngOnInit()之后加载 Angular life hooks设计说明,在构造函数之后,您可以访问的所有输入值。 您可以从init访问它 @Input() profileId: numb

在父组件中,我有:

<app-access-password [profileId]="getProfileId(kid.getId())"></app-access-password>

我收到了未定义的消息。为什么?

加载视图后需要访问,请将其移动到ngOnInit()方法


您必须在
ngOnInit()之后加载


Angular life hooks设计说明,在
构造函数之后,您可以访问的所有输入值。
您可以从
init
访问它

@Input() profileId: number;
ngOnInit() {
    console.log(this.profileId);
}

你可以在任何地方进入课堂内的任何地方

即使答案被接受,我也不同意。 您可以在
ngOnChanges()
中访问它。 甚至在
ngoninit()
之前调用了
ngOnChanges

ngOnChanges(changes : SimpleChanges){
 //changes.profileId will store both the previous and the current value . 
}

因此,只要
@Input()
启动(值从
null
更改为定义的值),就会自动调用
ngOnChanges
,因此您不必等待组件
ngOnInit

,因为该值尚未定义。再次检查
ngOnInit
,不要在构造中查看。请向您咨询提示
@Input() profileId: number;
ngOnInit() {
   console.log(this.profileId)
}
ngOnChanges(){
// you can access value everytime `this.profileId` value changes
}
@Input() profileId: number;
ngOnInit() {
    console.log(this.profileId);
}
@Input() profileId: number;
ngOnInit() {

}
console.log(this.profileId)
ngOnChanges(changes : SimpleChanges){
 //changes.profileId will store both the previous and the current value . 
}