A step-by-step guide to creating a new reference to an existing array without duplicating the array

Is there a way to create a new reference to an array without directly manipulating the array itself? I'm facing an issue with an Angular pipe that doesn't detect changes made through push/pop operations. I want to avoid solutions like this:

this.array = this.array.filter(e=>true)

Adding unnecessary complexity just to update the reference. I attempted another method, but it didn't work as expected (the pipe failed to detect any changes) and my lack of familiarity with JavaScript/Typescript prevents me from understanding why.

const newRef = this.array;
this.array = null;
this.array = newRef

I have a pipe that takes in an array of objects and an array of filters, and returns a filtered array of objects.

@Pipe({
  name: 'eventFilter'
})
export class EventFilterPipe implements PipeTransform {

  transform(events: EventDtos[], filters:Filter[]): any {
     //return filtered events
  }

Pipe usage:

<div  class="event" *ngFor="let event of events  | eventFilter:filters">
   html stuff
</div>

When adding or removing a filter from filters, the pipe's transform is not triggered, so I use the following code to force the transform call:

this.filters = this.filters.filter(e=>true)

However, I am unsure whether this method is faster than using an impure pipe. Ideally, I would like to stick with the pure pipe and update the filters reference without complicating things further.

Answer №1

Avoid using impure pipes as they can cause multiple change detections per second. Instead, consider copying the array for a better solution:

const newRef = this.array; // newRef references the array
this.array = null;
this.array = newRef // reference stays the same

You can also copy the array using simpler methods like spreading or slicing:

this.array = [...this.array];
// or
this.array = this.array.slice();

Alternatively, you can use a Subject and AsyncPipe to avoid copying the array:

@Component({...})
class MyComponent {
    readonly filters$ = new BehaviourValue<Filter>([]);

    ...
    addFilter(filter: Filter): void {
        this.filters$.value.push(filter);
        this.filters$.next(this.filters$.value);
    }
}
<div  class="event" *ngFor="let event of events | eventFilter:(filters$ | async)">
   html stuff
</div>

Answer №2

Do you happen to be in search of an impure pipe within Angular? By utilizing this method, your pipe will be updated automatically whenever there are input changes. For further details, check out the official guide here

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

Basic asynchronous JavaScript and XML (AJAX) call

I am currently learning about ajax and experimenting with a script that involves extracting information from a JSON object and displaying it on the document. Below is an example of the JSON file named companyinfo.json: { 'id':1, 'name&apos ...

An abundance of AJAX requests inundating the server

While working on a straightforward AJAX request, I encountered an issue where the server is sending back 3 responses instead of just one (you can see the example in the attached image). Could someone provide insight into why this might be happening? var ...

What is the best way to create shapes in Three.js using the mouse?

I'm searching for a way to enable users to draw their own cube, similar to the example here (try drawing a cube on a grid): Screenshot: Shapesmith has efficiently solved this using Three.js, but it relies on Backbone.js. I'm wondering if it&apo ...

jQuery: event not firing for dynamically loaded elements via AJAX

In my jQuery/HTML5 front-end setup (with backend-generated code omitted), I am currently using version 1.8.3 of jQuery with no version conflicts. The front-end calls the following functions: detailAjaxCall("\/client\/orders\/detailsLoad&bso ...

Creating interactive touch events on an HTML canvas with a scrollbar

Hello there, I'm currently working on developing a touch-enabled signing app that utilizes 2 HTML Canvases. The issue I am encountering is that when I scroll to focus on the second canvas, my ability to sign on it stops working properly. It appears t ...

Experiencing difficulties with certain npm CLI modules when using it as a task runner and build tool

After coming across an article about using npm as a build tool, I decided to give it a try for my tasks. However, I am facing an issue that has me stuck. Whenever I run a global command-line tool like JSLINT, JSHINT, or ESLINT using npm, the console always ...

JavaScript: Prototype event listener failing to trigger

I have a Magento test store with an onepagecheckout extension that utilizes a onepagecheckout.js file. I am trying to add 'click' event observers to the payment radio buttons, but nothing happens when they are clicked. The observers are being ad ...

Utilize Paper.js PointText to Obtain Baseline Coordinates instead of Starting from the Bottom Left Corner

Check out this Paper.js sketch. Click on "TEXT" to view the bounding box. It's worth noting that I configured the leading property to match the font size, though by default it is typically 1.2 times the font size as stated in the documentation. Why d ...

What is the best way to adjust the height and width of a div when it comes into view through scrolling?

How can I automatically and frequently change the size of my div when it is scrolled into view? HTML <div id="contact" class="fadeInBlock"> <div class="map"> <div class="pointer"> <div class="dot"></div& ...

Save the output to the server's file

Looking for a straightforward way to output the results of a json query in a more structured format. I currently have a file that fetches statistics from a json query and displays it using document.write. Now, I need these results to be stored in a csv or ...

Strategies for managing extended API requests during view loading

Hello, I am currently working on a Rails application focused on displaying user-generated content. Within one of my controllers, specifically the #show action, I am making an API call to generate recommendations for "up next" content. This API call typical ...

What is the most effective method for declaring callbacks on objects in Typescript?

I am currently working on a sidebar menu component that is connected to a service holding items in the menu. This allows multiple sources to make alterations to the menu as needed. Each item in the menu currently follows the SidebarItem interface: export ...

Utilizing Node.js to create macOS wrappers (such as .pkg and .app files)

Seeking guidance on packaging my Node.js application for macOS as a .pkg or .app file. Any recommendations on the most efficient method to accomplish this task? Any useful tutorials or tools would be greatly appreciated. Thank you, Asaf ...

Ways to organize JSON information in Angular by date basis?

I am working on a project where I need to organize multiple JSON objects into an array based on their date data, with the date field serving as the key. ...

JavaScript: Generate a JSON object with customizable key-value pairs

Suppose we have two arrays containing possible numerical values: var reg = [1000, 1010, 2050]; var ag = [100, 101, 102]; The objective is to create an object/json structure like this: { 1000 : [100, 101], 1010 : [100, 101, 102], 2050 : [100, 102]}; The ...

Error in Node.js: Unhandled promise rejection due to undefined value

We're currently facing an issue with the create user controller in Node.js Express. The problem arises when attempting to sign up on the front end, resulting in an error message: "Unhandled promise rejection error value is not defined." Although it ap ...

Changes in state are not reflected in component - Angular

Working on an Ionic project with Angular, I encountered an issue where changing the state in an alert's callback function does not reflect the changes in the UI. It seems like the component is not updating accordingly. How can I resolve this? async p ...

Updating an object within an array of objects with a replacement

Having trouble updating an object in an array of objects. Here is the initial array: myArray = [ {id: 0, description: "some description", status: "initial status", function: someFunction()}, {id: 1, description: "some descripti ...

Uncovering the types of objects in TypeScript

Can TypeScript infer the type based on the content of an object? For example: type MyKeyList = | "A" | "B" | "C" ; type MyType<T extends MyKeyList> = { type: T, value: T extends "A" ...

Angular - Server side - The initial response time is extraordinarily prolonged

https://i.sstatic.net/U6dPP.png My website - => It is built on Angular 12 SSR (running on node) The total time taken to render the page is approximately 6 seconds, with the initial server-side page taking around 4 seconds (even though it has a si ...