1

I am wondering why this is working:

<div *ngFor="let image of recipesList | slice:0:10">
   <div>{{image.recipe_id.food_name}}</div> <!-- Outputs a list of food names -->
</div>

And why I am not able to pass this recipesList (array of objects) data into a component

<app-planning [recipeData]="recipesList"></app-planning>

Planning component:

@Component({
  selector: 'app-planning',
  templateUrl: './planning.component.html',
  styleUrls: ['./planning.component.css']
})
export class PlanningComponent implements OnInit {

   @Input() recipeData: [];

   constructor() {
   }

   ngOnInit(): void {
      console.log(this.recipeData); // Returns an empty array
   }

}
12
  • recipeList or recipesList? Commented Feb 2, 2021 at 9:10
  • @Giannis recipesList, excuse me. Commented Feb 2, 2021 at 9:14
  • 1
    It seems you get the recipesList via API? If so it's empty when the component is initiated. Commented Feb 2, 2021 at 9:20
  • 1
    ngOnInit is called way before the HTML-template is being rendered and its content runs. You will most likely want to use ngOnChanges in order to check if the input value changed and react on it. Commented Feb 2, 2021 at 9:21
  • 1
    @PhilippMeissner okay great thanks! You made my day ;) Commented Feb 2, 2021 at 9:30

1 Answer 1

1

This is because @Input change detection works only with immutable objects. There are many articles about it.

In short if you push into input array - it will not work, but if you update reference to an array - it will work.

<app-planning [recipeData]="recipesList"></app-planning>

// Component
recipesList.push(newItem) // View will not be updated

recipesList = [...recipesList, newItem]; // View will be updated
Sign up to request clarification or add additional context in comments.

2 Comments

I don't see how the reference to the structure would in any way produce the error OP describes. It's a lifecycle issue, not a reference issue.
Robbert said that recipeData returns empty array but not undefined. So it means array is already constructed, and according to provided solution it is constructed in a parent component

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.