Reputation: 674
I'm trying to send value which I'm getting from web service to another component but the problem is that I'm getting empty value in that another component while I can see that the value is present when I do console.log() in the current component.
AppComponent
ts
level: string = '';
getCustomer(id: string) {
this.isLoading = true;
this.customerService.getOne(id)
.subscribe(
(data) => {
this.level = data.level;
console.log(this.level); // Here I can see the value
},
(error) => {
this.errorMessage = error;
},
);
}
html
<div class="col-lg-8">
<app-other-component [active]="level"></app-other-component>
</div>
AppOtherComponent
ts
@Input() active: string;
ngOnInit() {
console.log(this.active); // Here I'm getting an empty string
}
I think that this line is executing <app-other-component [active]="level"></app-other-component>
before the value of 'level' is even filled.
How can I resolve this? thanks.
Upvotes: 2
Views: 1400
Reputation: 39482
Try wrapping the div in an *ngIf
, if you don't want the app-other-component
to be visible before the value is set from the web service:
<div class="col-lg-8" *ngIf="level">
<app-other-component [active]="level"></app-other-component>
</div>
And yeah as Yousef suggested, you will get the updated @Input
value in ngOnChanges
and NOT IN ngOnInit
. ngOnChanges
is the function that gets called on a component every time one of its @Input
property changes. So you'll get the updated @Input
property in there:
@Input() active: string;
ngOnChanges() {
console.log(this.active); // Here You'll get the updated `active` string.
}
Upvotes: 4
Reputation: 2078
I guess that is because of 'this' pointer in callback function (which does not point to the component). Change it to 'self' like that
let self = this;
this.customerService.getOne
...
(data) => { self.level = data.level; }
Upvotes: 0