1

In parent component I have:

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

Where getProfileId(kid.getId() returns number if kid. I can see this value in template:

{{getProfileId(kid.getId())}} it is not empty.

WhenI try to get profileId value inside component app-access-password:

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

I got undefined message. Why?

1
  • 1
    Because the value is not defined yet. Check again in ngOnInit, not in the constructor Commented Aug 31, 2018 at 12:07

5 Answers 5

3

you need to access after the view has been loaded, move it to ngOnInit() method

@Input() profileId: number;
ngOnInit() {
   console.log(this.profileId)
}
Sign up to request clarification or add additional context in comments.

Comments

2

Even though the answer is accepted ,i would like to differ . You can access it in ngOnChanges() . ngOnChanges is called even before ngOnInint() .

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

so as soon as the @Input() kicks in(value is changed from null to a defined value) , ngOnChanges is automatically called so you don't have to wait for component ngOnInit

Comments

1

You will have to load after ngOnInit()

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

Comments

1

Angular life hooks design says, all input value you can access after constructor. You can access it from init .

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

Comments

1
@Input() profileId: number;
ngOnInit() {

}
console.log(this.profileId)

you can access inside class any anywhere

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.