如何获取child组件Angular中的输入参数?

How to get input parameter in child component Angular?

在 parent 组件中我有:

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

其中 getProfileId(kid.getId() returns 数字如果孩子。我可以在模板中看到这个值:

{{getProfileId(kid.getId())}}不为空

当我尝试在组件 app-access-password 中获取 profileId 值时:

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

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

需要在view加载完成后访问,移到ngOnInit()方法

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

您必须在 ngOnInit()

之后加载
@Input() profileId: number;
ngOnInit() {
   console.log(this.profileId)
}
ngOnChanges(){
// you can access value everytime `this.profileId` value changes
}

Angular life hooks 设计说,constructor 之后你可以访问所有输入值。 您可以从 init 访问它。

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

}
console.log(this.profileId)

您可以在任何地方访问 class

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

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

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