Explore various types of content on a blog using Angular's ngFor directive

I am trying to display a list of categories for a Blog in Angular using ngFor. However, I am facing an issue where it is displaying some categories multiple times, as if it is pulling in all the blogs instead of just the categories that are shared among them. I hope my question was clear.

Here is the code snippet from my HTML file:

<aside class="categories">
     <h2 class="aside-title">Categories</h2>

     <ul *ngFor="let data of datas; index as i">
        <li class="nav-elipse-blue"><a [routerLink]="['/page', datas.category]" title="Blog CSS 
        articles">{{ data.category.name }}</a></li>
     </ul>

</aside>


Answer №1

It seems like there is a need to eliminate duplicates from your array.

According to this solution, you can achieve that with the following code:

const uniqueCategorias = datas.filter((value, index) => {
  const _value = JSON.stringify(value);
  return index === obj.arr.findIndex(obj => {
    return JSON.stringify(obj) === _value;
  });
});

and then implement it like this:

 <ul *ngFor="let data of uniqueCategorias; index as i">
    <li class="nav-elipse-blue"><a [routerLink]="['/pagina',datas.category]" title="Blog CSS 
    articles">{{ data.category.name }}</a></li>
 </ul>

In your TypeScript file, add:

uniqueCategorias;

getUniqueCategorias(){
    uniqueCategorias = datas.filter((value, index) => {
        const _value = JSON.stringify(value);
        return index === obj.arr.findIndex(obj => {
            return JSON.stringify(obj) === _value;
        });
    });
}

Answer №2

To simplify your code, consider creating a separate variable called 'categories' for your class instead of fetching the list directly from the database. To extract unique categories, you can utilize JavaScript's "set" data structure to eliminate duplicates:

uniqueCategories = new Set(data.map(item => item.category.name))

Angular:

@Component({
  selector: 'component'
  templateUrl: 'component.html'
})
export class Component {
  data = ....
  uniqueCategories = new Set(this.data.map(item => item.category.name))
}

HTML

<ul *ngFor="let category of uniqueCategories">
  <li>{{category}}</li>
</ul>

Answer №3

To begin with, eliminate any duplicate elements from the array before utilizing *ngFor directive.

There are various ways to remove duplicates:

  1. Utilizing Set

    let data = ['A', 'B', 'A', 'C', 'B'];
    let uniqueData = [...new Set(data)];
    
  2. Using forEach() and include() :

     let data = ['A', 'B', 'A', 'C', 'B'];
    
     let uniqueData = [];
     data.forEach((c) => {
        if (!uniqueData.includes(c)) {
        uniqueData.push(c);
      }
     });
    

Although there are other methods available, these ones are more user-friendly.

Once you have done that, in your HTML

     <ul *ngFor="let data of uniqueData">
        <li>{{category}}</li>
     </ul>

Answer №4

filterCategories(data: any){
 let categoriesArray = [];
 let uniqueCategories:any;
  data.forEach((item, index) => {
    categoriesArray.push(item.category.name);
    uniqueCategories = categoriesArray.filter(function(item, pos, self) {
      return self.indexOf(item)===pos;
    })

     
  });
  return uniqueCategories;

}

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

persistent image in HTML affecting the layout of the header

I have been struggling with positioning a sticky image above my navigation bar. Here is the code for the sticky image: img.sticky { position: -webkit-sticky; position: sticky; top: 0; width: 200px; z-index: 1000; } <div> <a href=" ...

What is the approach taken by Angular when it comes to managing dependency injection for a variety

In my project, I've designed an abstract class that serves as a foundation service for my other two services. Below is the snippet of code for this abstract class: import { Injectable } from '@angular/core'; export interface Book { title ...

Jquery AutoComplete: Finding the ID of the selected item

I have successfully implemented an auto-complete field that fetches data from a database. The issue I'm facing is when a user selects an item from the autocomplete results, I need to save the corresponding id in a hidden field. Here is the code snipp ...

Getting the date from an XHR header in Angular2: A step-by-step guide

Is it possible to retrieve a date from XHR Header Response? https://i.sstatic.net/ErMMh.jpg I attempted to include '{observe: 'response'}' as options constructor(private http: HttpClient) { } getAllTemps() { return this. ...

Tips for effectively identifying TypeScript SyntaxKind within TSLint

While creating custom TSLint rules, I encountered a reliability issue with (ASTObject).kind across different TypeScript versions. For instance, in TypeScript version 3.4.5, the values for enum ts.SyntaxKind are ImportDeclaration = 249 and ImportClause = 2 ...

How can Vue be used to dynamically alter a string within an input field by incorporating the status of checked checkboxes?

Yesterday, I stumbled upon a concise Vue presentation on YouTube before answering a technical question on Stack Overflow. The question involved generating checkbox elements based on a string of text containing '1's and '0's, with the ch ...

The 'path' property is not found on the 'ValidationError' type when using express-validator version 7.0.1

When utilizing express-validator 7.0.1, I encounter an issue trying to access the path field. The error message indicates that "Property 'path' does not exist on type 'ValidationError'.: import express, { Request, Response } from " ...

In Vue.js, the 'select' option is consistently set as the default choice

Encountering an unusual issue with a select field in vue.js. Desired outcome: a select field with no default option selected. In regular html, this is easily achievable. Here is the jsfiddle Link: https://jsfiddle.net/odsf3awr/ <select id="test" s ...

Encountering the "TypeError: document.getElementById(...) is null" error message while utilizing react.js in conjunction with chart.js

I am encountering an issue while using react and chart.js together to create a bar chart. The problem lies in the fact that chart.js requires the use of canvas tags, and we need to locate this tag and insert the bar chart within it using the traditional do ...

Using custom properties with RouteComponentProps from react-router-dom

In my project, I have a component named Navbar that relies on the location object from history, which is defined in RouteComponentProps. I attempted to include a custom prop in my component like this: interface IProps{ title?: string } class Navbar ex ...

Send a request to an API using Django REST framework

I'm currently working on code in Angular 2: sendPost(){ let headers = new Headers(); headers.append('Content-Type', 'application/json'); let requestOptions = new RequestOptions({headers: headers}); requestOption ...

What is the best way to transfer a jQuery variable to PHP variables in order to use them in a Select Query?

<script type='text/javascript'> $(window).load(function(){ $("body").click(function(){ var s = window.getSelection(); s.modify('extend','backward','word'); ...

Using Javascript to dynamically populate dropdown options based on radio button selection

I am in the process of developing a basic form that allows users to input the frequency of a specific report. Initially, users were only able to enter days of the week. However, due to changes in demand for certain reports, options such as workday and day ...

Cloud-based Functions in Firebase and Firestore

I've been attempting to run a Firebase cloud function for making an atomic (batch) update in an Angular 5 project whenever a new customer is created. Despite my efforts, I keep encountering this error and have been unable to pinpoint the issue: cons ...

A guide on viewing the output of an AJAX request using Python and Selenium

Currently experimenting with Selenium testing on a Django website. I recently implemented a feature to track javascript errors through Google Analytics. How can I create a test to verify that when a javascript error occurs, an AJAX request is triggered a ...

What is the best way to manage files in production using Next.js?

I've been working on a Next.js app for file exchange and am looking to deploy it. During development, the app saves dropped files in the root public folder and retrieves them from there using the <a> tag with an href attribute of uploads/{filena ...

How can AngularJS achieve ng-repeat functionality with multiple variables similar to ng-init?

When using ng-init, you have the ability to utilize multiple variables: ng-init="var1=value1; var2=value2" I attempted something similar with ng-repeat but unfortunately it did not work as expected ng-repeat= "var1 in var1s; var2 in var2s" Is there a p ...

Adjust the jQuery.animate function based on the specific value

When the button with the class name btn is clicked, the element with the class name img-box will transition with animation. I want to adjust the animation based on the current position of the img-box. After the first click on the button, the element mo ...

Designing a user interface that consists of numerous distinct components

Challenge I'm faced with a dilemma regarding site A, which is built using React. Specifically, I need to find a way to integrate smaller React components into site A whenever a user navigates to a specific page within the site. Each of these smalle ...

Exclude certain APIs from utilizing basic authentication in Fastify

I currently have two APIs set up: /auth and /no-auth. My goal is to only use basic authentication for one of them. To implement this, I am using the fastify-basic-auth plugin with fastify in a node environment. The /auth route should require authenticat ...