How to access a specific element in an array using Angular 4

Within my Angular view, I have declared a variable called data with the following values:

[{"name":"science", count: 3},
 {"name":"action", count: 1},
 {"name":"thriller", count: 1},
 {"name":"article",  count: 1},
]

" I am attempting to extract the count value for the names "science" or "article" in an HTML file.

I have tried the following approach:

 <span ng-repeat="item in data| filter: {name: "science"}"> 
    {{ item.count }} 

 </span>

However, this does not return any results. I suspect it is due to the filter. How can I achieve this? Any assistance would be greatly appreciated.

Answer №1

To create a custom pipe in Angular, you can follow this example -

import {Injectable, Pipe, PipeTransform} from 'angular2/core';

@Pipe({
    name: 'myfilter'
})
@Injectable()
export class MyFilterPipe implements PipeTransform {
    transform(items: any[], args: any[]): any {
        return items.filter(item => item.id.indexOf(args[0]) !== -1);
    }
}

You would use the pipe like this in your template -

*ngFor="let element of (elements | myfilter:'123')"

Answer №2

To begin, it's important to note that you are confusing AngularJS (version 1.x) syntax with Angular (version 2+) syntax. In Angular, you should utilize ngFor along with a custom pipe for filtering data.

<span> <tr *ngFor="let item of data | scienceFilter:'science'"> {{ item.count }} </span>

Your custom pipe implementation should look like this:

@Pipe({
    name: 'scienceFilter'
})
@Injectable()
export class ScienceFilterPipe implements PipeTransform {
    transform(items: any[], type: string): any {
        return items.filter(item => item.id.indexOf(type) !== -1);
    }
}

AVOIDING THE USE OF FILTER FUNCTION

count: number;

Then, in your component, you can do this:

this.count = this.items.filter(t=>t.name ==='science').length;

Finally, in your HTML template:

<span> 
    {{ count }}
</span>

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

Testing the functionalities in the link function of a directive

When working with some of my directives, I often add functions to the scope in order to manage specific logic for that directive. An example of this would be: link: function(scope, element, attrs) { scope.doStuff = function() { //perf ...

Prevent click-through on overlaying divs in Leaflet maps

Is there a way to prevent an overlaying div on a leaflet map from being clickthrough? I tried setting pointer-events: none and auto on the overlaying div, but it didn't work. Setting pointer-events to none resulted in the radiobutton not being clickab ...

"Assigning an array as a value to an object key when detecting duplicates in a

Let's assume the table I'm iterating through looks like this: https://i.stack.imgur.com/HAPrJ.png I want to convert each unique value in the second column into an object, where one of the keys will hold all values from corresponding rows. Here& ...

Position the div in the center of a container that is 100% width and has floating elements with dynamic widths

I am looking to align 3 divs inside a container div, with the arrangement of [LEFT] [CENTER] [RIGHT]. The container div should be 100% wide without a fixed width, and I want the center div to stay centered even when resizing the container. The left and ...

Unable to implement styling to an HTML element using Javascript

Having very limited experience with Javascript, I decided to incorporate a feature on my webpage where the navbar changes size as the user scrolls down. The only way to achieve this was through the use of Javascript. Including the .js file in my HTML docu ...

Converting an Excel formula expression into JavaScript code

I am trying to implement the formula from Excel using the JSON object provided below. I have done the computations, but there seems to be an error as the result is not exact. If anyone has any ideas about it, I would appreciate your input. Thank you. I ju ...

CSS Style in Safari does not conceal Div on Tailwind

When switching the screen from desktop to mobile in ReactJS/Tailwind, I have hidden certain images using the following code: <div className="flex shrink flex-row justify-between w-[60%] h-[25%] sm:w-[95%] sm:h-[52%] mb-[-10px] mt-[-15px] lg:mt-0&qu ...

Property of a general object

I am working with an Interface export interface ChartDataResponseI { consumption: string generation: string measure_name: string point_delivery_number: string self_coverage: string time: string } My goal is to create a generic object property ...

Hover over a DOM element to highlight it, similar to the functionality of the inspect tool

Our website features a bookmarklet that triggers an inspect-like highlighter when a user clicks a button. We are aiming for this functionality to be compatible across different browsers. To achieve this, we must be able to detect the DOM element during mo ...

Material-Table does not allow resizing of columns if there are more than 5 columns present

I'm currently using the material-table library to present my data. Despite my attempts, setting a fixed size for each of my 19 columns isn't working as intended. Using width: 45% doesn't produce the expected visual result. Also, implementing ...

Issues encountered when using Three.js raycasting to position objects above a plane

My heightmap-based plane is not working with raycasting, and I'm also having trouble placing an object above the hovered triangle. UPDATE: By commenting out the height section (pgeo.vertices[i].z = heightmap[i] * 5;), it seems to work inconsistently. ...

Endless Node.js HTTP requests

I am facing an issue with my node.js http.request call while trying to access an external API (specifically the Openstack API). Although the request is successfully sent and I receive a response, the request does not finish immediately after receiving the ...

The information is not appearing in the dropdown menu

The select tag for chapters is not displaying the result from the query properly. Instead of showing in the select tag, the chapter names are being displayed as echo statements. <!doctype html> <html> <head> <meta charset="utf-8"> ...

incorporating SVG directly into a Leaflet popup using R

There have been examples suggesting that integrating SVG graphics into Leaflet popups is achievable, such as this one: seeking examples of SVG graphics in Leaflet popups Another illustration can be found here: Creating a graph within a leaflet popup using ...

Is it possible to include an argument in an unnamed function in Node.js without assigning it to a variable?

Coming from a C/C++ background, I've been struggling with grasping the syntax of node.js. After searching online for code examples to explain blocking and non-blocking operations, I stumbled upon a piece that has left me perplexed for hours. Despite m ...

The dynamic addition of divs to the HTML body is causing them to overlap

Check out this functional plunker that is nearly complete. The current issue I am facing is with the chat divs being dynamically added to the body using $compile, but they all have the same CSS class and end up overlapping each other, like so: .chat-wind ...

Convert the HTML string received from the backend API into an image and display it within the Angular mat-card

Currently, I am working on a project that involves using CK editor to create a template. The HTML string is saved in nodejs and then retrieved through a get API. My goal is to display this HTML string as an image inside a mat-card. I have attempted using h ...

One way to transfer data from the back end into a two-dimensional array is by retrieving the data and then transforming it into the desired format before sending it to

How can I format backend data into a specific format using JavaScript? Even though I retrieve data from the backend, json_encode($myarry) does not display my data. $query = "SELECT * FROM LOCATIONS"; $result= mysql_query($query); while($row = mysql_fetch ...

Unable to locate the module '/workspace/mySQL/node_modules/faker/index.js'

Hi there, I'm currently facing an issue while trying to run the app.js file in my project through the terminal. It keeps showing me an error message that I am unable to resolve. To provide some context, I have already installed the faker package using ...

Angular 2 Element Selection: Dealing with Unrendered Elements

This form consists of three input fields: <div> <input *ngIf = "showInputs" #input1 (change)="onTfChnage(input2)" type="text"/> <input *ngIf = "showInputs" #input2 (change)="onTfChnage(input3)" type="text"/> <input *ngIf = "showInp ...