Ensure that the ngOnChanges method is properly implemented by utilizing the Angular Lifecycle Interface OnChanges

A warning from Tslint is indicating that the method ngOnChagnes lifecycle hook should implement OnChanges. Interestingly, changing ngOnChanges to OnChanges resolves the warning.

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

}


 

Answer №1

requires the implementation of both OnInit and OnChanges interfaces in Angular

It is important to remember that whenever you use an Angular lifecycle hook, you must also include the corresponding implements interface in the controller class.

Answer №2

When defining the ngOnChanges() function within the OnChanges interface in Angular, it is important to note that the parameter it accepts must be of type SimpleChanges and not SimpleChange. It is worth mentioning that Angular will still recognize the usage of ngOnChanges() as a lifecycle hook even if the OnChanges interface is not implemented. However, without specifying the correct type for the parameter, errors could potentially arise.

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

ngOnChanges(changes: SimpleChanges) {
  ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PHP loader encountered an error: Module "." not found

My current challenge involves attempting to utilize a PHP file instead of an HTML file as the templateUrl for an Angular component. ... @Component({ selector: 'app-register-form', templateUrl: require('php-loader?./register-form.compone ...

Tips for soothing the TypeScript compiler

It seems like TypeScript is heavily influenced by Microsoft's interpretation of the DOM and JavaScript. But what if I'm not concerned with Internet Explorer and Edge? Unfortunately, I'm encountering issues with TypeScript... For instance, w ...

Tips for implementing dynamic properties in TypeScript modeling

Is there a way to avoid using ts-ignore when using object properties referenced as strings in TypeScript? For example, if I have something like: const myList = ['aaa', 'bbb', 'ccc']; const appContext = {}; for (let i=0; i< ...

Ionic 2: Trouble adding a component to a page

I have successfully created a new component and added it to my app, but I am facing an issue where an error message keeps appearing when I try to include it in my page. No provider for MyExample Even though I have already added the component to the app.m ...

Moving the starting directory of a NodeJS application on Azure

My NodeJS app on Azure was initially written in Javascript with the app.js file located in the root directory. This file was automatically detected during deployment via Git. Recently, I converted the app to Typescript and now have a build directory, with ...

Using Angular 4 to populate a form and ensure it remains untouched

Designed an update form that is pre-populated with information. I am aiming for the button to be inactive until any changes are made within the form The form group utilizes valueChanges to detect when information has been modified However, even when I u ...

Angularfire2 with Firebase - receiving notifications for added child in queried list

Is it possible to utilize the "child_added" event with queried lists? For example: this.curUserPosts = this.af.database.list('/posts', { query: { orderByChild: 'user/id', equalTo: id } }).$ref.on("child_added", (c ...

Various strategies for improving the performance of a NodeJs server-side API that conducts calculations

My current project involves making an API call from the client (Angular v10) to the server-side (NodeJs v12). This API call is responsible for performing calculations on a large dataset, which typically takes around 7-10 minutes to complete. The main goal ...

Stop the inheritance of static components in a feature module by protecting the router-outlet

I am in the process of dividing my app into multiple feature modules. Currently, I am using only the router-outlet inside a component within a feature module. However, this approach brings along all the static components such as the navbar and footer. How ...

What is the method for identifying if an ion-content element contains a scrollbar?

Is it possible to dynamically show or hide elements based on the presence of a scrollbar within ion-content? Specifically, I want to display a button for loading more items in a list when there is no scrollbar, and hide it when a scrollbar is present (thus ...

Troubleshooting TypeScript Modules in Visual Studio 2015 Update 2: Fixing the 'require' Undefined Error

While working in Visual Studio 2015 Enterprise with Update 2 installed, I decided to create a new TypeScript project called TypeScriptHTMLApp1 using the default template and settings. As part of this project, I added a new TypeScript file named log.ts and ...

Enhance filtering capabilities in FormGroup with an autocomplete input feature for more options

Seeking to implement a basic autocomplete textbox that allows selection from a filtered list of objects displayed by name. For instance, with an array of Country objects containing properties like countryName, countryCode, and countryId, the goal is to fi ...

Ways to verify and incorporate https:// in a URL for a MEAN Stack application

When extracting the URL from API data, my code looks like this: <div class="row copy-text"> <a href="{{copy.Url}}" target="_blank" style="text-decoration: underline !important;">{{copy.Title}}</a> </div> I am interested in ve ...

What is the best way to loop through all mat-checkboxes in Angular 5?

Is there a way for me to automatically have check-1, check-2, and check-3 all checked when I click on check-all? <form> <mat-checkbox type="checkbox" class="select_all"> Check all </mat-checkbox> <br> < ...

Angular utilizes ZoneAwarePromise rather than a plain String output

I expected the giver code to return a string, but it is returning ZoneAwarePromise. Within the service: getCoveredPeriod() { let loanDetails = this.getLoanDetails().toPromise(); loanDetails.then((res: any) => { const coveredPeriodStart ...

Is there a specific directive in Angular that allows for variable declarations using the "

This interesting piece discusses the usage of a let-name directive in the template: <ng-template #testTemplate let-name> <div>User {{ name }} </div> </ng-template> Can anyone tell me if this is a part of the standard ang ...

Issue with Angular: event.key doesn't register as shft+tab when pressing Shift+Tab key

Our website features a dropdown menu that can be opened and closed by clicking, revealing a list of li items. However, we are currently experiencing an issue with keyboard focus navigation. When the Tab key is pressed, the focus properly moves from one li ...

The Typescript Select is displaying an incorrect value

Here's the code snippet I've been working with: <select #C (change)="changeSelect(zone.id, C.value)"> <option *ngFor="let town of townsLocal" [attr.value]="town.data" [attr.selected]="town.data === zone.town && 'selected& ...

Incorporating the Angular2-wizard module into your project

My Angular project is based on the Angular Quickstart seed. I have been developing my own components and now I am looking to integrate the Angular2-wizard npm package. To install the package, I used the following command: $ npm install angular2-wizard -- ...

What is the best way to pass an array of 8-digit strings from an input in Angular to a Node.js backend?

I am currently facing a challenge where I need to pass an array of 8 digit strings from an Angular input to a Node.js endpoint. The method below works perfectly fine when passing a single string, but how can I handle an array of 8 digit strings as input? ...