POV
POV

Reputation: 12015

How to get input parameter in child component Angular?

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?

Upvotes: 1

Views: 91

Answers (5)

CruelEngine
CruelEngine

Reputation: 2841

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

Upvotes: 2

harkesh kumar
harkesh kumar

Reputation: 883

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

}
console.log(this.profileId)

you can access inside class any anywhere

Upvotes: 1

Harun Or Rashid
Harun Or Rashid

Reputation: 5947

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);
}

Upvotes: 1

Abhishek Ekaanth
Abhishek Ekaanth

Reputation: 2567

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
}

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222682

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

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

Upvotes: 3

Related Questions