Amar Ratna Shakya
Amar Ratna Shakya

Reputation: 588

Angular Lifecycle Interface OnChanges should be implemented for method ngOnChanges

Tslint is sending a warning indicating that OnChanges should be implemented for method ngOnChagnes lifecycle hooks. If I change ngOnChanges to OnChanges then the warning is not there.

import { Component, Input, OnInit, Output, EventEmitter, SimpleChange, OnChanges } from '@angular/core';

import { Order } from '../../../../core/orders';

import { CartItem } from '../../../../core/orders';
import { User } from '../../../../core/auth/_models/user.model';

declare var $: any;

@Component({
  selector: 'app-order-summary',
  templateUrl: './order-summary.component.html',
  styleUrls: ['./order-summary.component.scss']
})
export class OrderSummaryComponent implements OnInit, OnChanges {
  @Input() cartDetails: Order;
  @Input() sellerDetail: User;
  @Input() productCost: number;
  @Output() closeOrderSummary = new EventEmitter<string>();
  @Output() checkoutCart = new EventEmitter<string>();
  @Output() updateItemQty = new EventEmitter<string>();
  @Output() updateProductSelected = new EventEmitter<string>();

  cartList: CartItem[] = [];
  isCartEmpty: boolean;

  constructor() {}

  ngOnChanges(changes: SimpleChange) {
    for (const propName in changes) {
      if (propName === 'cartDetails') {
        const change = changes[propName];
        this.cartList = change.currentValue;
        this.isCartEmpty = (change.currentValue.length === 0);
      }
    }
  }

  ngOnInit(): void {
  }

  onUpdateItemCount(item, direc) {
    const payload = { item, direc };
    this.updateItemQty.emit(payload);
  }

  onUpdateProductSelected(value, item) {
    const payload = { value, item};
    this.updateProductSelected.emit(payload);
  }

  goBackToMain() {
    this.closeOrderSummary.emit();
  }

  onCheckoutCart() {
    this.checkoutCart.emit();
  }

}


 

Upvotes: 2

Views: 6904

Answers (2)

Barremian
Barremian

Reputation: 31105

The parameter of ngOnChanges() function declared in the OnChanges interface accepts parameter of type SimpleChanges and not SimpleChange. As mentioned in the comment of other answer, usage of function ngOnChanges() without implementing the OnChanges interface would also be accepted as a life-cycle hook by Angular. But the type error you're receiving would not have been thrown, that could've led to other issues.

import { Component, Input, OnInit, Output, EventEmitter, SimpleChanges, OnChanges } from '@angular/core';

ngOnChanges(changes: SimpleChanges) {
  ...
}

Upvotes: 3

Patrick Kelleter
Patrick Kelleter

Reputation: 2771

implements OnInit, OnChanges

is missing. whenever you use an Angular lifecycle hook you should also add the corresponding implements interface to the controller class.

Upvotes: 9

Related Questions