2

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.

2
  • Probably because the call to get the data is async and it its not yet present at the time the ngOnInit() is called Commented Nov 23, 2018 at 9:35
  • 2
    You will have to implement OnChanges to get the updated value Commented Nov 23, 2018 at 9:37

2 Answers 2

4

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.
}
Sign up to request clarification or add additional context in comments.

3 Comments

But if he need the component rendered when the level is not setted your answer is not quite good.
@JacopoSciampi, I think that's something that he'll have to explicitly specify in the OP. We can't just assume that right? :)
@SiddAjmera Thanks! it worked perfectly in my situation
0

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

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.