Identify duplicate value assignments for a property using ngOnChanges

Essentially, I am working with an array of objects and my goal is to pass the index of a selected object from the array to another component using @Input.

The issue arises when I try to select the same item twice because the ngOnChanges function does not recognize it as a change when the value remains the same (e.g., going from 1 to 1). As a result, I am unable to select the same object consecutively.

Child Component:

@Input('editAppointmentIndex') editAppointmentIndex: number;

ngOnChanges(changes: SimpleChanges) {
    console.log(changes);
    if (changes.editAppointmentIndex && changes.editAppointmentIndex.currentValue != undefined) {
      // Perform actions on the selected object
    }
}

Parent Component:

<child-component [editAppointmentIndex]="currentAppointmentIndex"></child-component>
currentAppointmentIndex: number;

onEdit(i) {
    this.currentAppointmentIndex = i;
}

Sibling Component:

<button class="edit" (click)="onEdit(i)">Edit</button>
@Output() onEdit_: EventEmitter<number> = new EventEmitter<number>();

onEdit(i) {
    this.onEdit_.emit(i);
}

Answer №1

When the value remains unchanged, it does not trigger a new event, so OnChanges will not be activated.

I personally don't see it as too troublesome to include an object with the index to solve this issue. Here is my suggestion:

selectedItemIndex = {};

onSelect(i) {
  this.selectedItemIndex = { index: i };
}

Then you can access the index like this:

if (changes.selectedItemIndex.currentValue && changes.selectedItemIndex.currentValue.index != undefined) {
  console.log(this.selectedItemIndex.index)
}

DEMO: StackBlitz

Answer №2

Another approach is to utilize the @Input decorator in combination with a setter method.

previousValue: number;
@Input()
set appointmentEditIndex(newValue: number) {
  if (newValue && newValue !== this.previousValue) {
    // Implement desired actions with the selected object
   }
   this.previousValue = newValue;
}

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

Best approach for managing Angular dependencies: Is it acceptable to link to a TypeScript file other than its corresponding component.ts in a component.html file?

My friend and I recently had a disagreement about a file in our project called experiment-row.component.html. The code in question looked like this: *ngIf="experimentsPageService.isRegularStatusIconVisible(experiment)" I argued that it is not go ...

Connecting Angular modules via npm link is a great way to share common

Creating a project with a shared module that contains generic elements and components, such as a header, is my goal. This shared module will eventually be added as a dependency in package.json and installed through Nexus. However, during the development ph ...

How can you create a type in Typescript that is composed of a specific property taken from another type?

I'm still in the process of understanding typed languages, but imagine I have the following scenario: export interface Person { id: number; name: string; } const persons: Array<Person> = [ { id: 1, name: 'foo', }, { ...

Angular Express Route Guide

I've encountered an issue with my express angular app. When I am on a specific URL like http://localhost:4007/login and refresh the page, I keep getting an error. I've tried multiple solutions to fix it, but nothing seems to work. Here is a snip ...

Issue with Angular 2 (Ionic 2): Struggling to properly display Component within Page

I have successfully created an Angular 2 Component: import {Component, View} from 'angular2/core'; @Component({ selector: 'sidemenu' }) @View({ templateUrl: 'build/pages/menu/menu.html', }) export class Menu { } Howev ...

Three.js and Angular - the requested function cannot be found

In my latest project, I created a basic application using Angular 4 and three.js to display a cube. The main part of the code resides in an Angular component called ViewerComponent, where the cube is rendered. I've simplified the relevant part of the ...

Press the key to navigate to a different page

I have an input field for a search box. I want it so that when I enter my search query and press enter, the page navigates to another page with the value of the input included in the URL as a query string. How can I achieve this functionality? Thank you ...

A tutorial on ensuring Angular loads data prior to attempting to load a module

Just starting my Angular journey... Here's some code snippet: ngOnInit(): void { this.getProduct(); } getProduct(): void { const id = +this.route.snapshot.paramMap.get('id'); this.product = this.products.getProduct(id); ...

What is the best way to bundle my Language Server along with my client?

Currently, I am in the process of developing a language server for VSCode which consists of both a client and a server that communicate over RPC. Fortunately, the official documentation includes a fully functional example, where the language server is div ...

Is there a way to incorporate an external JavaScript file into a .ts file without the need for conversion?

I have an external JavaScript file that I need to utilize in a .ts file without performing any conversion. Does anyone know how to use it within TypeScript without the need for conversion? ...

What is the concept of NonNullable in typescript and how can it be understood

In TypeScript, the concept of NonNullable is defined as type NonNullable<T> = T extends null | undefined ? never : T For instance, type ExampleType = NonNullable<string | number | undefined>; Once evaluated, ExampleType simplifies to type Exa ...

Implementing Service Communication

I created an Angular Application using the Visual Studio Template. The structure of the application is as follows: /Clientapp ./app/app.module.shared.ts ./app/app.module.client.ts ./app/app.module.server.ts ./components/* ./services/person-data.service. ...

Using TypeScript, take advantage of optional chaining in conjunction with object destructuring

After updating typescript to version 3.7.4, I find myself trying to modify my code. My code is straightforward: interface Test event: { queryStringParameters: { [name: string]: string } | null; } } const test:Test = (event) => { // const { n ...

"Error: Retrieving the body data from the Express request

I am having trouble retrieving the JSON data using TypeScript in the req.body. It keeps showing up as undefined or an empty object. const signUpUser = ({ body }: Request, res: Response): void => { try { res.send(body) console.log(body) } cat ...

The Java value is not returned by the Observable<boolean> stream

I'm currently working on making a request to the backend for a boolean value using observables, but I'm struggling to figure out the best approach between .map and .subscribe. return this.http.put({url}, credentials, this.requestOptions) .ca ...

What could be causing the issue with converting a Firestore timestamp to a Date object in my Angular app?

Currently, I am developing an Angular project that involves using a FireStore database. However, I have encountered a problem with the setup. Within my Firestore database, I have documents structured like the example shown in this image: https://i.sstatic ...

Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test. The view is up and running, but I'm facing some roadblocks as I work on ...

Use RxJS to ensure one observable waits for another observable to emit a non-null value

I am currently facing an issue with my setter function in TypeScript. In this setter, I assign a class member observable called systemAreasOptions$. The reason behind doing this in the setter is because it needs to wait for the observable mappedItem$ to ...

Using Typescript to deliver the parent component's props to its children prop

I have a goal to create a versatile component that can accept different props based on its usage in the project. The component should output its children prop along with all the given props (flow-through) and potentially some new constants calculated based ...

Navigating with Angular: Every time I refresh the page or enter a specific URL, Angular automatically redirects to the parent route

In my CRM module, I have created a custom Routing Module like this: const routes: Routes = [ { path: 'crm', component: CrmComponent, children: [ { path: '', redirectTo: 'companies', pathMatch: 'full&ap ...