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

What is the best way to incorporate both static text and dynamic variables within a mat tooltip in Angular?

Is it possible to combine static text and dynamic variables in a mat tooltip using Angular? <span class="trim" [matTooltip]="Updated at test.updated by test.updated_at.name" > {{test.created_by.email}}</span> Any assis ...

Using node-fetch version 3.0.0 with jest results in a SyntaxError stating that import statements cannot be used outside a module

Recently, I've been updating my API to utilize node-fetch 3.0.0. One major change highlighted in their documentation is that node-fetch is now a pure ESM module. Click here for more information on the changes This update caused some of my unit tests ...

Attempting to utilize the setInterval function in Ionic 4 to invoke a specific function every second, unfortunately, the function fails to execute

Working with Ionic 4 has been a breeze for me. Recently, I encountered a situation where I needed to update the value of an ion-range every second by invoking a function. However, despite successfully compiling the code, the changeMark function never seeme ...

A guide to teaching TypeScript to automatically determine the type of dynamic new() calls

One of the challenges I'm facing involves dynamically creating subclasses and ensuring that the factory function is aware of the subclass's return type. While I can currently achieve this using a cast, I am exploring options to infer the return ...

Prevent Angular from performing change detection on specific @Input properties

Within my Angular component, there are extensive calculations that take place when changes are detected. @Component ( selector: 'my-table', ... 400+ lines of angular template ... ) class MyTable implements OnDestroy, AfterContentInit, On ...

The alterations made to a single dropdown option are causing ripple effects across all other dropdowns

There is an add button that continuously adds a div container containing two dropdowns. The selection in one dropdown affects the data in the other dropdown. When the add button is clicked, a second div with both dropdowns is added. However, changing the ...

Typescript's async function failing to execute properly

I'm currently facing an issue with my code and I'm a bit puzzled as to where the problem lies. The console is displaying the correct data for this.allNominations, but it appears that the third for-loop is not being executed at all. As a result, t ...

What is the best way to send ServerSideProps to a different page in Next.js using TypeScript?

import type { NextPage } from 'next' import Head from 'next/head' import Feed from './components/Feed'; import News from './components/News'; import Link from 'next/link'; import axios from 'axios&apo ...

Can dynamic forms in Angular 2 support nested forms without relying on formBuilder?

I'm familiar with implementing nested forms in reactive form, but I'm unsure about how to do it in dynamic form within Angular 2. Can nested forms be implemented in dynamic forms in Angular 2? ...

"Troubleshooting the placement problem in Angular Material's md-menu

I am currently utilizing the md-component for Angular 2 from Angular Material. I am carefully following the documentation's instructions on how to integrate it into my project, but I am encountering an issue where the menu opens up below the trigger. ...

Designing a visual showcase with interactive tab links for image selection

I have been working on developing an Angular component that simulates a tab gallery functionality, inspired by this example. Below is my HTML structure: <div class="gallery-container"> <div class="display-container"> ...

Does Nativescript successfully utilize AOT Compilation even with the `Compiler` package still included?

I'm running this command: npm run ns-bundle --android --build-app --uglify The command is successful (you can find the complete log here). After navigating to the report folder (generated by webpack-bundle-size-analyzer), I found these two files: ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

Parameters in Typescript decorators

Can someone help me understand the various parameters of a Typescript decorator? function myDecorator(target) { // do something with 'target' ... } In the given example, I am aware that 'target' represents the function/class to wh ...

The functionality of *ngIf fails to display the template when the array is void of any elements

view image descriptionHello, I am new to using Angular and I'm encountering an issue with the ngIf directive not working as expected in the tutorial. I have included my code snippets below. Any assistance would be greatly appreciated. My component: i ...

Utilizing Regex to Authenticate a CAGE Code

Our task is to create a RegEx pattern that can accurately validate a CAGE Code A CAGE Code consists of five (5) positions. The code must adhere to the following format: The first and fifth positions must be numeric. The second, third, and fourth position ...

Is it possible for the ionic ionViewDidEnter to differentiate between pop and setRoot operations?

I am facing an issue with my ionic 3 page where I need to refresh the data on the page only if it is entered via a navCtrl.setRoot() and not when returned to from a navCtrl.pop(). I have been using ionViewDidEnter() to identify when the page is entered, bu ...

Encountering issues when trying to combine Sequelize with TypeScript

As I attempted to transition my NodeJs application to TypeScript, I encountered issues with Sequelize. Upon attempting to implement the code from a website, an error occurred: This expression is not constructable. Type 'typeof import("/home/de ...

What is the best way to inject services into non-service class instances in Angular 2?

Here is my current approach, but I'm curious about the recommended practice for working with Angular2? ... class MultitonObject { _http: Http; constructor (appInjector: Injector) { this._http = appInjector.get(Http); } } var ap ...

Best practices for managing data loading with composition API and onBeforeRouteUpdate

I have a Vue 3 single-page component that contains the following script: export default defineComponent({ props: { id: String, }, setup(props) { const error = ref<boolean>(false) const thisCategory = ref<CategoryDetails>() ...