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

Getting around relative paths in an Angular application hosted by NGINX

I am using NGINX to host my Angular application. The frontend is accessible at http://localhost/, and the backend can be accessed at http://localhost/api/. While most of my configuration works correctly, I am encountering an issue with a relative path in a ...

There are several InputBase elements nested within a FormControl

There seems to be an issue: Material-UI: It appears that there are multiple InputBase components within a FormControl, which is not supported. This could potentially lead to infinite rendering loops. Please only use one InputBase component. I understand ...

The Angularfire library encountered an issue when trying to access the 'push' property of a null object

I am currently in the process of creating a new object in the database for an assessment. Right now, I have hardcoded it to test its functionality, but ultimately, it will be dynamic based on user input from the view. However, I am encountering an error th ...

There seems to be an issue with AFNetworkActivityLogger in Swift 3.0 Xcode 8 as it is failing to log

I have implemented the following code to log AFNetwork activity: func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let consoleLogger = AFNetworkActiv ...

"When a class extends another class and utilizes properties within a static property, it essentially becomes

I have been encountering challenges with generics in TypeScript for quite some time now. My current setup is as follows: First, there is a generic class defined as: class Entity { public static schema = {}; } Then, there is a class that extends the ...

Looking to arrange an object by the value of a nested object in Typescript/Angular?

I'm currently developing an Angular 9 application focused on covid-19 cases, and I need to arrange my objects by the value of nested objects. Here is the dataset that I want to organize alphabetically based on the 'state' field values: stat ...

Issue encountered when attempting to save items in the browser's local storage

I'm encountering an issue: ERROR Error: Uncaught (in promise): DataCloneError: Failed to execute 'put' on 'IDBObjectStore': Position object could not be cloned. Error: Failed to execute 'put' on 'IDBObjectStore& ...

What is the best way to utilize a React type as props for a custom component?

To make my component work properly, I am required to pass the inputmode as props from an external source. The acceptable values for <input inputMode=<valid values>> are outlined in the React types (node_modules@types\react\index.d.ts) ...

Incorporating an Angular 2 application into HawtIO as a plugin

Can we integrate an entire Angular2 application as a plugin in HawtIO? By doing this, we aim to leverage HawtIO as the main container for our OSGi applications, each with its own user interface, allowing us to easily detect and display each UI web app with ...

Having trouble retrieving the state value of an array in React?

Having issues with ...this.state.users in React My React Code: handleChange(i, e) { const { name, value } = e.target; let users = [...this.state.users]; users[i] = { ...users[i], [name]: value }; this.setState({ users }); } Snippet from ...

Retrieve the specific type of property from a generic data structure

I am currently working on a project where I need to determine the type of property within a given Type: type FooBarType { foo: string, bar: number } The function would be structured like this: getType<K extends keyof T>(key: K): string. The ...

Guide to creating a dynamically adjustable index position for jsonb_set

I have a straightforward json dataset and I am looking to append a new key:value pair to it. select elem, position from jsonb_all_testing,jsonb_array_elements(jsonb_col->'UserProfile') with ordinality arr(elem,position) where col1=2 The re ...

Uncovering Information from Geocodio API's JSON Data

Utilizing the Geocodio API, I am searching for congressional district information based on a provided address. Below is my code snippet: from geocodio import GeocodioClient import json client = GeocodioClient('MY API KEY') availible_office ...

Need to monitor a Firebase table for any updates

How can I ensure my Angular 2 app listens to changes in a Firebase table? I am using Angular2, Firebase, and TypeScript, but the listener is not firing when the database table is updated. I want the listener to always trigger whenever there are updates or ...

Challenges arise when attempting to break down an API into separate components rather than consolidating it into a

I've been struggling with this issue for a few days now. Problem Explanation: I am trying to use Axios to fetch data and store it in the state for each individual Pokémon. However, currently all the data is being rendered inside a single component w ...

Transforming time data from a MySQL database table into the ISO8601 format in order to generate a JSON feed within WordPress that can be utilized

I've created a custom WordPress action that retrieves data from a table and encodes it in JSON format for use with the FullCalendar JavaScript event calendar. The date fields retrieved from the table need to be formatted in ISO8601 standard. To clar ...

Sharing data across multiple components while navigating in Angular is a common requirement. By passing

I have a specific structure set up in my application: <div class="container"> <top-navbar></top-navbar> <router-outlet></router-outlet> <navbar></navbar> </div> The components I have include Top ...

Type Vue does not contain the specified property

I am encountering an issue where I am using ref to retrieve a value, but I keep receiving the error message "Property 'value' does not exist on type 'Vue'". Below is the code snippet causing the problem: confirmPasswordRules: [ ...

Angular generates a dynamic interface to fetch data from Wordpress REST API posts (special characters in property names are causing issues)

I've been developing a front-end Angular application that interacts with the Wordpress REST API to fetch and display post data. My goal is to create an interface to handle the responses and render the posts in the template. However, I encountered an ...

Converting JSON object to a string

I have an object that contains the value "error" that I need to extract. [{"name":"Whats up","error":"Your name required!"}] The inspector displays the object in this format: [Object] 0: Object error: "Your name required!" name ...