Transitioning from ng-repeat filter to Typescript

As I migrate my project from AngularJS to modern Angular 8, one of the steps is converting JavaScript code to TypeScript. During this process, I encountered a challenging issue with the `ng-repeat` filter feature.

Initially, my HTML template looked like this:

<div ng-repeat="menuItem in items| filter: vm.filterMenuItem">

I found it peculiar that when calling a function, there was no need to specify a passed argument.

Here is the JavaScript code:

function filterMenuItem(menuItem) {
  let paramFits = vm.filters.param === 0 || menuItem.param === vm.filters.param;
  let anotherParamFits = vm.filters.anotherParam === 0 || menuItem.anotherParam === vm.filters.anotherParam;

  return paramFits && anotherParamFits;
 }

Where vm.filters is a controller-level variable that can be modified from the template.

When I rewrote it in TypeScript:

filterMenuItem(menuItem: MenuItemClass) {
  let paramFits = this.filters.param === 0 || menuItem.param === this.filters.param;
  let anotherParamFits = this.filters.anotherParam === 0 || menuItem.anotherParam === this.filters.anotherParam;

  return paramFits && anotherParamFits;
}

...everything broke. AngularJS did not recognize the proper controller-level this inside the function, resulting in this being undefined.

Is there a way to maintain a custom filter function with TypeScript?

Answer №1

It is necessary to make adjustments to the custom filter function:

updateFilter(menuItem: MenuItemClass, filters) {
    return menuItem => {
      let paramFits = filters.param === 0 || menuItem.param === filters.param;
      let anotherParamFits = filters.anotherParam === 0 || menuItem.anotherParam === filters.anotherParam;

       return paramFits && anotherParamFits;
   }
}

Additionally, the HTML template should be updated as follows:

<div ng-repeat="menuItem in items | filter: vm.updateFilter(menuItem, vm.filters)">

The main modifications include:

  • Explicitly specifying the object (menuItem) and filter criteria (vm.filters) to be checked with the filter, passing them explicitly to the function without using this references.
  • The filter function should not only return a boolean value, but a predicate function with calculations within it.

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

What advantages does utilizing Jasmine Spy Object provide in Angular Unit Testing?

I have a question regarding unit testing in Angular using Jasmin/Karma. Currently, I am working with three services: EmployeeService, SalaryService, and TaxationService. The EmployeeService depends on the SalaryService, which is injected into its constru ...

The Mean Stack by Bitnami

After setting up the Mean Stack Manager, I encountered an issue. When running a command in the node terminal like console.log("Hello World"), it runs smoothly. However, if I place a Javascript sample file in any folder within the mean stack install directo ...

I noticed that while my shareService is effectively sending values in Angular 2, I encounter an issue where my other components are displaying default values instead

I'm in the process of developing an application using angular 2. I have a UserService that sends a value to other components indicating whether a user is logged in or not, and it's working correctly in terms of data transmission. The issue I&apos ...

Is there a way to customize the progress bar percentage in Ant design?

I am currently utilizing React JS and importing the Ant Design progress component (refer to https://ant.design/components/progress/). However, I am facing difficulties in dynamically editing the percentage of the progress bar using JavaScript after it has ...

IE11 and how it handles Typescript and promises

Currently, I am utilizing Typescript version 2.4.2 along with Webpack for compilation purposes. Despite successful compilation, when running my code on IE11, an error 'Promise' is undefined arises. Below is a glimpse of my tsconfig: { "comp ...

Observing the interconnections between services

Seeking advice on how to effectively monitor dependencies in order to ensure that their methods are being utilized within my services. I have streamlined my code to focus on the core issue. While I am able to test my service successfully, I also want to ve ...

Master the art of string slicing in JavaScript with these simple steps

I am attempting to utilize the slice function to remove the first three characters of a string within a JSON object. $(document).ready(function() { $.ajaxSetup({ cache: false }); setInterval(function() { $.getJSON("IOCounter.html", functio ...

Error: The function being called in <class> is not recognized as a function

I have a unique situation with my component setup export class Component1Component implements OnInit { public greetings: string =""; constructor(private greeter: Greeter) { } ngOnInit() { this.greetings = this.greeter.sayHello(); } } The structur ...

Exploring the Concept of Nested ViewModels in Knockout.js Version 3.2.0

I have a global view model that is applied to the main div and I also have other view models that I want to apply to nested elements within my main div However, I am encountering an issue: You cannot bind multiple times to the same element. Below is ...

Change occurring within a cell of a table that has a width of 1 pixel

In the code snippet below, there is a transition inside a table cell with a width of 1px to allow it to wrap its content. However, the table layout changes only at the end or beginning of the transition: var animator = document.getElementById("animator" ...

Updating .babelrc to include the paths of JavaScript files for transpilation

Using Babel, I successfully transpiled ES6 JavaScript to ES5 for the project found at I'm currently stuck on updating my .babelrc file in order to automatically transpile a specific ES6 file to a particular ES5 file. Can someone guide me on what cod ...

What Causes the "Not a String or Buffer Type" Unhandled Exception?

I've encountered an error that seems to be originating from the following line of code, even though I believe I am following the example correctly (viewable at https://www.npmjs.org/package/aws-sign). Any help or hints would be greatly appreciated. v ...

What is preventing this AJAX request from redirecting to the `/login` URL?

I'm currently developing a Node Express application with Handlebars. Although I receive a success message in the console, the URL doesn't change to /login, preventing the page from rendering. However, manually entering the URL localhost:3000/log ...

What is the best way to tidy up a function within a useEffect hook?

When updating state within a useEffect hook while using async/await syntax, I encountered an error regarding the cleanup function. I'm unsure how to properly utilize the cleanup function in this scenario. Error: Warning - A React state update was att ...

The deletion request using the form in Express is experiencing issues and not functioning properly

When attempting to delete data from a database using a form in node.js and express, I am encountering issues with the deletion process. It seems that there are only two methods available - get and post - and no specific delete method. router.js code rout ...

Choose the radio button by clicking using jQuery

I am attempting to use jQuery to select a radio button on click. Despite multiple attempts, I have been unsuccessful so far. Here is my current code: JS $(document).ready(function() { $("#payment").click(function(event) { event.preventDefault() ...

Toastr - encountering a problem with the settings

After invoking a toastr message using the following command: Command: toastr["success"]("foo") toastr.options = { "closeButton": false, "debug": false, "newestOnTop": false, "progressBar": false, "positionClass": "toast-bottom-right", "prev ...

Unable to display content within a map function

I am facing an issue with a map function in my code. The function is supposed to return a component with deconstructed properties. While the map itself is functioning correctly and I can see all the right values when I log them to the console, nothing is g ...

Transmitting a JavaScript file via a Node.js server

I have a NodeJS server that sends a JavaScript file to the client. However, the JavaScript file does not import the libraries it needs on the client side. I load these libraries on the client side before receiving the file. Why is the file unable to find t ...

Nested self-referencing in Typescript involves a structure where

Please note that the code below has been simplified to highlight a specific issue. The explanation before the code may be lengthy, but it is necessary for clarity. Imagine I have a Foo class that represents a complex object. interface Config { bars:{ ...