The ngFor directive in Angular should be used with the Filter pipe to ensure that

Having a Filter implemented in my Angular Project that fetches data from Firebase.

The current status in the Filter is as follows:

  • Name 1: Lea Muster
  • Name 2: Bruno Mustermann
  • Name 3: Lea Muster
  • Name 4: Gabriela Musterfrau

The goal is to show duplicate entries like "Lea Muster" only once in the filter:

  • Name 1: Lea Muster
  • Name 2: Bruno Mustermann
  • Name 4: Gabriela Musterfrau

Seeking advice on displaying unique values only.

Component.ts File:

import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { AngularFirestore } from '@angular/fire/firestore';

export interface Profile {
  topic: string;
  location: string;
  gender: string;
}

interface Gender {
  value: string;
  viewValue: string;
}

@Component({
  selector: 'app-filtermain',
  templateUrl: './filtermain.component.html',
  styleUrls: ['./filtermain.component.css'],
})
export class FiltermainComponent implements OnInit {
  people: Gender[] = [
    { value: 'mann-0', viewValue: 'Mann' },
    { value: 'frau-1', viewValue: 'Frau' },
    { value: 'norole-2', viewValue: 'Spielt mir keine Rolle' },
  ];
  profile: Profile[] | undefined;

  therapykind = new FormControl();

  therapyplace = new FormControl();

  constructor(private afs: AngularFirestore) {}

  ngOnInit(): void {
    console.log('Initializing');
    this.afs
      .collection<Profile>('profiles')
      .valueChanges()
      .subscribe((values: any) => {
        console.log(values);
        this.profile = values;
      });
  }
}

Component.html File:

<div>
  <h2>Where would you like to have your therapy?</h2>
  <mat-form-field appearance="fill">
    <mat-label>Choose your favorite location</mat-label>
    <mat-select [formControl]="therapyplace" multiple>
      <mat-option *ngFor="let profile of profile">
        {{ profile.location }}</mat-option
      >
    </mat-select>
  </mat-form-field>
</div>

Although I attempted using a pipe, it resulted in errors, so seeking further help.

Thank you!

Answer №1

Here's a suggestion for you to try out: Start by creating a new function that will generate a fresh array with unique values.

getUniqueArray() {
    const key = 'Name';  //Specify the key containing duplicate values.
    newArray = [...new Map(this.profile.map(item =>
    [item[key], item])).values()];
    return newArray ;   //This newArray will only have unique values.
}

Next, integrate this function into your code like so:

ngOnInit(): void {
  this.afs
  .collection<Profile>('profiles').valueChanges().subscribe((values: any) => {
    this.profile = values;
    this.profile = this.getUniqueArray();    
  });
}

I hope this provided solution proves beneficial to you.

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

Exploring the method to deactivate and verify a checkbox by searching within an array of values in my TypeScript file

I am working on a project where I have a select field with checkboxes. My goal is to disable and check the checkboxes based on values from a string array. I am using Angular in my .ts file. this.claimNames = any[]; <div class="row container"> ...

The PWA software encountered an issue where the checkForUpdate function never resolved

Despite my efforts, I have encountered an issue while working with the PWA for our application. The checkForUpdate and versionUpdates methods do not seem to resolve to any values. constructor( appRef: ApplicationRef, updates: SwUpdate, ) { ...

I'm diving into the world of Typescript and trying to figure out how to use tooltips for my d3 stacked bar chart. Any guidance on implementing mouseover effects in Typescript would be greatly

I am currently facing some issues with the code below and need guidance on how to proceed. I am new to this and unsure of how to call createtooltip. Any assistance would be greatly appreciated. The error message states that createtooltip is declared but n ...

Angular Material: styling issue with input clear button icon placement

I am currently working on implementing a feature in my first Angular application. I found this example on the official Angular Material website demonstrating how to create an input field with a clear button: https://material.angular.io/components/input/exa ...

Certain Material-UI components appear to lack proper styling

I found a tutorial on how to incorporate material UI into my app at this link: https://mui.com/material-ui/getting-started However, I noticed that some components are not styled as expected and customizing the theme seems to have no effect... This is how ...

Disable the yellow curly error lines in Visual Studio Code

Currently, I am utilizing VSCode with ESlint for Typescript development. I'm curious about how to turn off or remove the yellow curled error lines in my code editor, like the ones displayed in this example image: https://i.stack.imgur.com/Zdtza.png M ...

Upgrade from Next.js version 12

Greetings to all! I have recently been assigned the task of migrating a project from next.js version 12 to the latest version. The changes in page routing and app routing are posing some challenges for me as I attempt to migrate the entire website. Is ther ...

Transforming JavaScript to TypeScript in Angular: encountering error TS2683 stating that 'this' is implicitly of type 'any' due to lacking type annotation

While in the process of migrating my website to Angular, I encountered an error when attempting to compile the JS into TS for my navbar. After searching around, I found similar issues reported by other users, but their situations were not quite the same. ...

I am experiencing an issue with my date filter where it does not display any results when I choose the same date for the start and end dates. Can anyone help me troub

Having an issue with my custom filter pipe in Angular. When I select the same dates in the start and end date, it doesn't display the result even though the record exists for that date. I've noticed that I have to enter a date 1 day before or ea ...

Tips on connecting an Angular web application with Google authentication

Hello, I am exploring the Google Cloud Platform for the first time and need help with implementing Google sign-in on my Angular web application. I have searched for code solutions but haven't found anything useful yet. Can anyone recommend any documen ...

Best location to define numerous dialog components

Currently, I have 8 custom Modals that are called in various places within my app. These modals are currently located inside the app.component.html as shown below: <agc class="app-content" [rows]="'auto 1fr'" [height]=" ...

Jest test encounters an error due to an unexpected token, looking for a semicolon

I've been working on a Node project that utilizes Typescript and Jest. Here's the current project structure I have: https://i.stack.imgur.com/TFgdQ.png Along with this tsconfig.json file "compilerOptions": { "target": "ES2017", "modu ...

What could be causing my React Redux state to not trigger a re-render?

Having trouble with my redux state not triggering a re-render when using a selector. I'm new to react-redux and typescript, and despite following advice online about returning a new object from the reducer, my object is still not re-rendering even tho ...

Circular structure error occurred when attempting to convert an object to JSON, starting at an object constructed with the constructor 'Object'

I am facing an issue where I need to update a Medico from the collection, and I have successfully destructured the data of the Medico's name and email. Additionally, I have obtained the ID of the assigned hospital. However, I am having trouble sendin ...

Parsing the header parameter in a GET request from Angular within the Spring backend

Recently, I delved into Rest services in Spring and learned from a tutorial that sending parameters to the backend can be done securely through the following method: getCompanyDetails(username:string): Observable<CompanyObject>{ const headers = ...

Can the color of text be adjusted (to either white or black) based on the background color (in any color and format)?

To achieve a text color that contrasts well with any background, I need to make sure it's either black or white. The background in my app can vary in color and format, so finding the perfect solution has been challenging. Using mix-blend-mode doesn&a ...

Considering the move from AngularJS 1.4 to Angular 8 is a significant one, the question arises: should one opt to migrate to 1.5 before upgrading

After conducting extensive research, I am still unsure of the best approach for migrating a large, poorly structured program to Angular 8 (or at least Angular 7). The options of vertical slicing, horizontal slicing, or a complete rewrite all seem dauntin ...

Inferencing partial types in Typescript

I'm completely stuck on this and can't seem to figure it out without using a second function: interface Fixed { a: number } const fn = <A, B extends {} = {}>(b: B) => { return b } fn({ a: 1 }) // { a: number } fn<Fixed>({ a: 1 } ...

Is there a way to access a function or variable from within the scope of $(document)?

Whenever I attempt to utilize this.calculatePrice, it does not work and I am unable to access the external variable minTraveller from within the function. numberSpin(min: number, max: number) { $(document).on('click', '.number-spinner b ...

I'm curious, what is the exact function of ...state?

Just dipping my toes into NgRx (redux) within Angular and I'm a bit puzzled by the use of ...state in the code snippet below. My understanding is that it functions as spread operator, but I can't grasp why the data attributes from the Interface S ...