Detecting changes in Angular when the @Input() value remains the same

I have created an Angular Custom scroll directive that utilizes an @Input() to pass an HTML element as a parameter, allowing the scrollbar to move to that specific element.

However, I've encountered an issue where if I pass the same HTML Element multiple times, the Input only detects changes for the first time and then fails to detect any subsequent changes.

Is there a way to ensure that Angular detects changes even when the same input is passed?

@Input() set elementToScroll(element: HTMLElement) {
    if (element != undefined) {
        console.log(element); // Only detecting changes for the same input the first time
        this._osInstance?.scroll(
            { el: element, block: { y: 'begin' } },
            500
        );
    }
}

Answer №1

If you want to add a little extra flair, consider utilizing a neat "hack" by passing an object with your input like this: {element:element}

@Input() set elementToScroll(element:{element:HTMLElement}) {
    // Access the element by using element.element
    if (element.element != undefined) {
        console.log(element.element); 
        this._osInstance?.scroll(
            { el: element.element, block: { y: 'begin' } },
            500
        );
    }
}

// In the parent component, use something similar to this:

@ViewChild('move') myElement:ElementRef
click(){
   this.parameter={element:myElement.nativeElement}
}

Answer №2

To enhance your component, incorporate the OnChanges interface and execute the ngOnChanges method:

ngOnChanges(changes: SimpleChanges) {
    if(changes['myProperty']) {
        // myProperty has been altered
   }
}

If you assign the same value twice, this solution will only work or be activated once based on the type of value provided.

  • If myProperty is of type string, number, etc., it will only be triggered once
  • For complex types, the solution will function correctly

Review the console output in this example: https://stackblitz.com/edit/angular-ivy-rd8szx

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

Even after ensuring the proper type checking, I am still receiving the error message "Property 'message' does not exist on type 'object'"

I have the following code snippet: try { // api call } catch (error) { if (typeof error === 'object' && error !== null && 'message' in error) { if (typeof error.message === 'string') { if (error.me ...

Angular : How can a single item be transferred from an array list to another service using Angular services?

How to Transfer a Single List Item to the Cart? I'm working on an Angular web application and I need help with transferring a single item from one service to another service and also displaying it in a different component. While I have successfully i ...

Is it necessary to declare parameters for the super class constructor in Typescript React? If so, what would those parameters be?

I'm struggling to understand the specifics of the constructor in this code. Can anyone clarify what arguments the constructor for super() and constructor() should have? import * as React from "react"; import styles from "./ScriptEditor.module.scss"; ...

Issue with Angular: Child component not receiving data after successful parent component call

I'm currently working with a parent and child component setup. Within the child component, I have a button configured like this: //child.component.html <button mat-raised-button [disabled]="!form.valid || submitButtonDisable" type = 'Submi ...

Booking.com's embedded content is experiencing display issues

My current project involves adding a booking.com embedded widget. Initially, when accessing the main page, everything works perfectly - the map and booking widget are visible for ordering. However, if you switch views without leaving the page or closing th ...

I'm looking for a way to implement a jQuery-style initialization pattern using TypeScript - how can I

My library utilizes a jQuery-like initialization pattern, along with some specific requirements for the types it should accept and return: function JQueryInitializer ( selector /*: string | INSTANCE_OF_JQUERY*/ ) { if ( selector.__jquery ) return select ...

What is the most effective way to refresh SCSS in a current Angular project?

I'm in the process of updating the SCSS version within my angular project. From the beginning, I selected scss in the angular cli for this project, so I have been using SCSS already. However, now I need to incorporate a spacing library that requires t ...

The reason for my inability to include a fresh method in String.prototype using typescript

I attempted to extend the String.prototype with a new method, but I encountered an issue. interface String { newMethod(): void } String.prototype.newMethod = function() {} Although there were no errors in the typescriptlang.org playground, I received ...

Learn how to build an "Advanced Interface" in Angular Nativescript using nativescript-websocket

I am facing difficulties in implementing the "Advanced Interface" of nativescript-websocket in Angular/Typescript as I need to incorporate a custom sslFactory to trust all certificates. The issue is that when attempting to connect to the server, there are ...

Is there a way to dynamically assign values to [routerLink] based on the elements in an array?

Looking to create a dynamic routing within my template. The routing values are sourced from an array that is being iterated through with ngFor. Additionally, I need to perform some transformations on these string values. Any help would be appreciated. En ...

Achieve the capability to upload multiple files in Next.js using the upload.io integration feature

I'm currently using upload.io for uploads and replicate.com for an AI model on a specific app. I am able to upload one picture, but unfortunately, I am encountering issues when trying to upload multiple pictures. Can anyone identify the problem here? ...

I encountered an unexpected obstacle while reloading my Next.js application with animejs. The error message reads: "SyntaxError: Unexpected token 'export'." This unwelcome occurrence took place during the

Encountering an error with animejs when reloading my Next.js app: An unexpected token 'export' is causing a SyntaxError. This issue occurred during the page generation process. The error originates from file:///Users/.../node_modules/animejs/lib ...

Ways to share socket.io instance with other TypeScript modules

When it comes to exporting an io object obtained from initializing socket.io to my router module in typescript, I am unsure whether I should export the io object from the server.ts module or initialize socket.io in my router module. Are there any other rec ...

TypeScript enum type encompassing all potential values

One thing I have learned is that keyof typeof <enum> will give us a type containing all the possible keys of an enum. For example, if we have enum Season{ WINTER = 'winter', SPRING = 'spring', SUMMER = 'summer', AUT ...

Ways to access a property within an object using TypeScript

Can you help me extract the "attributes" array from this object and store it in a new variable? obj = { "_id": "5bf7e1be80c05307d06423c2", "agentId": "awais", "attributes": [ // that array. { "created ...

ConfirmUsername is immutable | TypeScript paired with Jest and Enzyme

Currently, I am experimenting with Jest and Enzyme on my React-TS project to test a small utility function. While working on a JS file within the project, I encountered the following error: "validateUsername" is read-only. Here is the code for the utilit ...

"Send the selected radio button options chosen by the user, with the values specified in a JSON format

My current task involves inserting radio button values into a MySql database using Angular. The form consists of radio buttons with predefined values stored in a json file. Below is an example of how the json file is structured: //data.json [{ "surve ...

Client side is receiving an unexpected format from the pyramid when using the __json__ method

As I'm configuring a Pyramid back-end along with an Angular front-end application, I encounter an issue. When Angular sends an http GET request to Pyramid, the data received on the Angular side is not as expected. It seems like the id is being recogni ...

What is the reason behind Angular FormControl applying the 'disabled' attribute in the DOM but not the 'required' attribute?

After transitioning my form logic from the template to FormGroup & FormControl objects, I noticed that when a FormControl is disabled in Angular, the 'disabled' attribute for the field is automatically updated in the DOM. However, when I modi ...

Exploring the Validation of Forms in Angular for Practical Implementations

I'm curious to know whether creating a simple form validation process can really be as complicated as it seems, or if I may be overlooking something. It's fairly straightforward to demonstrate the power of form validation in a tutorial setting. ...