How to conceal duplicate items in Angular2

In my Angular 2/4 application, I am fetching data from a web API (JSON) and displaying it in a table. In AngularJS, I use the following code:

<tbody ng-repeat="data in ProductData | filter:search | isAreaGroup:selectedArea">
    <tr style="background-color:burlywood;cursor:pointer" data-toggle="modal" data-target="#editProduct"
     ng-click="selectItem(data); setSelected(data.ProductId)">
        <td class="text-right">{{data.Id}}</td>
        <td>
            <strong ng-show="ProductData[$index].ProdShifts.Product.Id != ProductData[$index-1].ProdShifts.Product.Id">
            {{data.ProdShifts.Product.Name}} : {{data.ProdShifts.Product.Name}}
            </strong>
        </td>
        <td class="text-center"><strong>{{data.ProdShifts.Shift}}</strong></td>
        <td class="text-center">{{data.WorkersGroup}}</td>
        <td class="text-center"><span>{{data.ProductionDay | date : 'd.MM.yyyy'}}</span></td>
        <td class="text-center">{{data.ProdShifts.StartTime | date:'HH:mm'}} - {{data.ProdShifts.EndTime | date:'HH:mm'}}</td>
        <td class="text-right">{{data.Norm | number : 2}}</td>
        <td class="text-right">{{data.Workers | number : 2}}</td>
        <td class="text-right">{{data.Productivity | number : 2}}</td>
        <td class="text-center"><input type="checkbox" ng-model="data.Active" disabled /></td>
    </tr>
 </tbody>

However, when I attempt to implement this in Angular 2/4, it doesn't work as expected. Here is what I have tried:

<tbody>
    <ng-template ngFor let-data [ngForOf]="(result) | filter:filterByName | areaFilter:filterArea" let-i="index" let-f="first" let-l="last">
        <tr style="background-color:burlywood;cursor:pointer"
        (click)="lgModal.show()">
            <td class="text-right">{{data.Id}}</td>
            <td>
                <strong [hidden]="duplicateResult">
                    {{data.ProdShifts.ProdLines.Product.Name}} : {{data.ProdShifts.Product.Name}}
                </strong>
            </td>
            <td class="text-center"><strong>{{data.ProdShifts.Shift}}</strong></td>
            <td class="text-center">{{data.WorkersGroup}}</td>
            <td class="text-center"><span>{{data.ProductionDay | date : 'd.MM.yyyy'}}</span></td>
            <td class="text-center">{{data.ProdShifts.StartTime | date:'HH:mm'}} - {{data.ProdShifts.EndTime | date:'HH:mm'}}</td>
            <td class="text-right">{{data.Norm | number: '1.2'}}</td>
            <td class="text-right">{{data.Workers | number: '1.2'}}</td>
            <td class="text-right">{{data.Productivity | number: '1.2'}}</td>
            <td class="text-center"><input type="checkbox" [(ngModel)]="data.Active" disabled /></td>
        </tr>
    </ng-template>
</tbody>

How can I display only the first value and hide duplicates in {{data.ProdShifts.Product.Name}}?

[Edit] I found an issue with the `ngStyle` usage. Here is the corrected code without using a pipe:

<td>
  <strong  
  [ngStyle]="{display: ( i > 0) ? (( result[i].ProdShifts.Product.Id === result[i-1].ProdShifts.Product.Id ) ? 'none':'block'):'block'}">
    {{data.ProdShifts.ProdLines.Product.Name}} : {{data.ProdShifts.Product.Name}}
</strong>

Answer №1

If you need to customize how data is filtered, you can create a unique pipe for that purpose.

For an example of how this can be done, check out the following link: http://plnkr.co/edit/E7HlWeNJV2N3zwPfI51Q?p=preview

declare var _: any; // lodash, not strictly typed

@Pipe({
    name: 'uniqFilter',
    pure: false
})
@Injectable()
export class UniquePipe implements PipeTransform {
    transform(items: any[], args: any[]): any {

        // using lodash uniqBy function
        return _.uniqBy(items, args);
    }
}

Here's how you can use it:

<div>
    <ul>
        <li *ngFor="let data in ProductData  | uniqFilter: 'Name'">{{ account.accountNumber }}</li>
    </ul>
</div>

Answer №2

To display only distinct values in the template, you can either utilize a personalized pipeline or filter out the unique elements from the output beforehand.

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

Change JSON data structure to HSTORE format

I am currently running PostgreSQL 9.4. In the beginning, my USERS table had a DETAILS field with an HSTORE data type. I successfully switched the column type from HSTORE to JSONB using the following command: ALTER TABLE users ALTER COLUMN details TYPE js ...

An issue occurred while trying to run Ionic serve: [ng] Oops! The Angular Compiler is in need of TypeScript version greater than or equal to 4.4.2 and less than 4.5.0, but it seems that version 4

Issue with running the ionic serve command [ng] Error: The Angular Compiler requires TypeScript >=4.4.2 and <4.5.0 but 4.5.2 was found instead. Attempted to downgrade typescript using: npm install typescript@">=4.4.2 <4.5.0" --save-dev --save- ...

Guide on converting pandas table data into a customized JSON structure?

Consider the PANDAS table linked below for illustration: sample_pandas Inquiry: How might one generate a json file to output the following: {"data": [ [a1, a2, a3], [b1, b2, b3], [c1, c2, c3] ] } It is understood that in pandas, each entry can be ret ...

Using Json.NET to Append JObject to existing JArray

Struggling with a seemingly simple piece of code, can't seem to figure it out. JObject obj = new JObject { "Name", "John" }; JArray array = new JArray(); array.Add(obj); // receiving error message: "Can not add Newtonsoft.Json.Linq.JValue to Newtons ...

Encountering the error "No exported member ɵɵFactoryDef in Angular 8 when trying to access /node_modules/@angular

Encountering the following error when attempting to run the ng serve command and also in ng build --prod. ERROR in ../node_modules/mat-file-upload/lib/mat-file-upload.component.d.ts:21:21 - error TS2694: Namespace '"/root/storeproj/node_modules/@angu ...

Transform JSON data into a Java object with a modified format

I need to convert a JSON string representing an object into a Java object B with a different structure. My current approach involves creating a Java Object A that mirrors the JSON structure, using Jackson for JSON to A conversion, and Dozer with XML mappin ...

guide for dynamically loading angular modules

In my application, I have three modules: home, moduleA, and moduleB. Within my app component, I am making a call to an API called session which returns a value named mode. Depending on the mode being moduleA or moduleB, I need to lazy load the respective m ...

Enter data into the appropriate columns

Within my Angular 6 application, I am creating a table with the following structure: Html: <table> <thead> <tr> <th> Property Details &nbsp; &nbsp; &nbsp; &nbsp; ...

Obtaining data from JSON arrays

My current challenge involves extracting data from the following link: and storing it in my database. However, I am encountering difficulties with manipulating the array in order to retrieve the last unix datetime. Despite multiple attempts to extract th ...

Utilizing Material Design Icons within Angular 4: A Step-by-Step Guide

I'm looking to integrate the icons available on into my angular 4 project. However, the website's instructions only cover how to do this in Angular 1.x () Can someone guide me on how to include Material design icons so that I can use them like ...

Eliminating Elements from Array

Hey there, I'm working with an array in R: A<-array(c(1:12), dim=c(6,2)) I'm trying to filter out the first 3 rows where the value in the first column is less than 3, and for the last 3 rows I want to keep those where the value in the first c ...

Error: The promise was not caught due to a network issue, resulting in a creation error

I'm trying to use Axios for API communication and I keep encountering this error. Despite researching online and attempting various solutions, I am still unable to resolve the problem. Can someone please assist me? All I want is to be able to click on ...

Exploring Angular5 Navigation through Routing

I have been working with Angular routing and I believe that I may not be using it correctly. While it is functional, it seems to be causing issues with the HTML navbars - specifically the Info and Skills tabs. When clicking on Skills, a component popup s ...

Issue encountered while trying to iterate through an observable: Object does not have the capability to utilize the 'forEach' property or method

I am currently following the pattern outlined in the hero.service.ts file, which can be found at this link: https://angular.io/docs/ts/latest/guide/server-communication.html The Observable documentation I referenced is available here: When examining my c ...

Extract information from a nested document contained within an array

Is there a way to access information from an inner document embedded within an array in MongoDB using Spring? { "project" : "proj001", "sourcevo" : [ { "name" : "HpAlm", "type" : "database", "source" ...

Why does my useEffect consistently execute after the initial rendering, despite having specified dependencies?

const [flag, setFlag] = React.useState(false) const [username, setUsername] = React.useState('') const [password, setPassword] = React.useState('') const [errorUsername, setErrorUsername] = React.useState(true) const [er ...

Find the total number of duplicate elements in a JavaScript array

I'm using an ajax call to retrieve values from a JSON structure and pushing them into a JavaScript array with .push for each iteration. However, I have multiple instances of the same value (e.g. person's name) in the array and I want to count the ...

Organize array elements based on their values - using javascript

I am currently exploring the most effective approach to divide an array into multiple arrays based on specific operations performed on the values within the array. Imagine I have an array like this: var arr = [100, 200, 300, 500, 600, 700, 1000, 1100, 12 ...

*ngFor fails to update existing table rows and instead just appends new rows

In my project using Sonic 3, I am utilizing the SQLite plugin to insert data into a SQLite database. Subsequently, I retrieve this data and display it in my template. This is the TypeScript file: saveData() { this.sqlite.create({ name: 'i ...

Organize JSON data based on the timestamp

What is the most effective method for sorting them by timestamp using jquery or plain JavaScript? [{"userName":"sdfs","conversation":"jlkdsjflsf","timestamp":"2013-10-29T15:30:14.840Z"},{"userName":"sdfs","conversation":"\ndslfkjdslkfds","timestamp" ...