angulartypescriptlifecyclengonchanges

problems with ngOnChanges when updating an array


I have an array that is getting updated from another component (the update is happening and Strings are getting added into the array I've checked it with a test button) but ngOnChanges wont detect any change. What is wrong with my code?

The change I apply is array.push().

import { Component, OnInit, Input, OnChanges } from '@angular/core';
import {MatAccordion} from '@angular/material/expansion';

@Component({
  selector: 'app-cart',
  templateUrl: './cart.component.html',
  styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit, OnChanges {
  totalPrice = 0;
  constructor() { }
  @Input() Products: Array<String>;

  ngOnChanges() {
    console.log(this.Products)
  }

  ngOnInit(): void {
    
  }

}

Solution

  • You are using incorrect syntax for ngOnChanges. Use the following:

    ngOnChanges(changes: SimpleChanges) {
       console.log(changes.Products.currentValue);
    }
    

    Also, note that unless the reference to the array changes the above lifecycle hook will not get triggered. If you want the lifecycle hook to be triggered then change the reference each time you push an element to the array. For eg:

    .ts

    myArr = [];
    
    add() {
      this.myArr = [...this.myArr, String(Math.random())];
      console.log(this.myArr)
    }
    

    .html

    <button (click)="add()">Add more numbers</button>
    
    <app-cart-component [Products]="myArr"></app-cart-component>