0

I have a Sidebar inside a component like below:

<div class="container-fluid">
   <div class="row">
      <div class="col-8">
         <!--Main Content-->
      </div>
      <div class="col-4">
         <app-sidebar [qdyk]="dyk"></app-sidebar>
      </div>
   </div>
</div>

In the parent component I set the dyk property:

ngOnInit() {
    // Load the current question
    this.currentQuestion();
  }

// Load the current question
  currentQuestion() {
    // Get the current question from the API
    this.questionService.getCurrentQuestion().subscribe(res => {
      // Load the question to angular
      this.loadQuestion(res);
    });
  }

loadQuestion(sequence: any) {
    // Load the whole sequence object...
    this.sequence = sequence;
    this.question = this.sequence.currentQuestion;
    this.dyk = this.question.didYouKnow;
    console.log(this.dyk);
}

The above console log returns the text I was expecting from the API, but when I try to pass this down to the child I get an undefined

@Input() qdyk: string;

ngOnInit() {
    // Show DYK Value from Parent
    console.log(this.qdyk);
  }

Passing a string value and bypassing the question loading works and outputs the string to the console passed from parent to child (for example: <app-sidebar [qdyk]="'Some Text'"></app-sidebar>) - it's just when I pass in the dynamic value?

2 Answers 2

1

You are using the wrong hook to check the values as they are being delayed and initially it will be undefined . Use ngOnChanges() -

@Input() qdyk: string;

ngOnChanges() {
    // Show DYK Value from Parent
    console.log(this.qdyk);
  }
Sign up to request clarification or add additional context in comments.

Comments

1

This scenario is common cause when calling the child component the value of dyk is undefined. As ngOnInit() lifecycle hook runs only when it loads, the console.log() gave undefined. But once loadQuestion() is called on parent component, it will be reflected on childcomponent but ngOnInit() won't run again, so it isn't be displayed on the console. If you had declared the this.dyk in ngOnInit of parent component instead of loadQuestion(), the console.log() will surely display your dynamic value. That's why when you directly passed a string as input it was shown in console. To console the values on child component use ngOnChanges() lifecycle hook

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.