Creating a dynamic selection in Angular without duplicate values

How can I prevent repetition of values when creating a dynamic select based on an object fetched from a database?

Below is the HTML code:

<router-outlet></router-outlet>
<hr>
<div class="row">
  <div class="col-xs-12">
    <form [formGroup]="catSelection">
      <select formControlName="transactionControl">
    <option [ngValue]="transaction" *ngFor="let transaction of transactions">{{transaction.category}}</option>
    </select>
    </form>
  </div>
</div>

And here is the TypeScript code:

export class TransactionsComponent implements OnInit {
  transactions: Transaction[]
  catSelection: FormGroup;

  constructor(private dfService: DataFetchingService) { }

  ngOnInit() {
    this.catSelection = new FormGroup({
      'transactionControl': new FormControl(null)})
    this.loadPosts()
  }

  loadPosts() {
    this.dfService.fetchData().subscribe(
      posts=>{
        this.transactions=posts; 
        console.log(this.transactions)
      }
    )
  }
}

You can view a live example on Stackblitz: https://stackblitz.com/edit/angular-6ni1pg

Answer №1

If you want to retrieve unique values, using a data structure like Set can be very helpful. Take a look at this example: https://stackblitz.com/edit/angular-vdch68

// transactions.component.ts

this.dfService.fetchData().subscribe(
      posts=>{
        // By creating a set of categories here,
        // the array this.transactionCategories will only contain unique values
        this.transactionCategories = new Set<string>(posts.map(p => p.category));
      }
    )

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

Trying out cellRenderer in Angular's Ag Grid with Jest to validate values

I am facing an issue where I need to test the actual values displayed in a column of an Ag Grid table. These values are formatted using a cellRenderer based on specific conditions. In my Jest test, I have experimented with various approaches: Using fixtu ...

Looking to adjust the height of a foreignObject element within an SVG?

Looking to dynamically change the height of a foreignObject within an SVG, while also needing HTML elements inside it (working with ngx-graph). <foreignObject x="1" y="1" width="335" [height]="foreignObjHeight(node.Dat ...

The Angular error dialog triggered by the ErrorHandler fails to show any information when encountering a TypeError

I've managed to get a lot of this example up and running with help from other sources, but I'm still facing one lingering issue. When I deliberately throw an error, the Error Dialog functions as expected. It also works correctly when throwing an ...

Accessing a targeted XML file within a document using Office.js in a Word Add-In

I am struggling to load the file named item1.xml from the ..\customXml folder of my document into my Word Add-In. So far, I have attempted the following: var url = Office.context.document.url + '\\customXml\\item1.xml\& ...

Complete set of keys within a type

In my TypeScript project, I am working with an API (specifically OData API) to retrieve data. This API allows the selection of specific fields to retrieve. For example, api/some/getbyid(42)?$select=x,y,z can be used to get fields x, y, and z, along with s ...

Issues arise when attempting to use the Android KeyUp, KeyDown, and KeyPress events in conjunction with Angular2

I am encountering an issue where I consistently receive a keyCode of 229 in Android Chrome browsers when running either: <input type="text" (keydown)="testKeyCodes($event)"/> <!-- or --> <input type="text" (keyup)="testKeyCodes($event)"/& ...

Is the ng bootstrap modal within Angular failing to show up on the screen

In the midst of working on my project, I encountered an issue with opening a modal using ng bootstrap. Although I found a similar thread discussing this problem, it did not include bootstrap css. I decided to reference this example in hopes of resolving t ...

Modify an array by incorporating values from another array that have a matching property

I have two arrays that look like this let array1 = [{ 'id': 1, 'name': 'A' }, { 'id': 2, 'name': 'B' }, { 'id': 3, 'name': ' ...

Utilizing a function from a library in an Object within a Typescript environment

Currently, I am working on assigning a field within my interface to a function from an external library in the following manner: import { Accelerometer, } from 'expo-sensors'; type SensorInterface = { permChecker: () => Promise<Permiss ...

Exploring the potential of Angular2's WebSocket service by efficiently accessing the parent component

I need some assistance with implementing WebSockets in my angular2 application. However, I've encountered a minor issue that I can't seem to solve. Here's what I have so far: I've created a service that has a method for creating a WebS ...

Encountered an error while attempting to install the DataTables npm package in an Angular

I am trying to add datatables to my angular application. Upon running ng add angular-datatables An error code is displayed (refer to the image). error image The cause of this error is unknown to me. Please review the package.json file as well. package.j ...

I encountered difficulties connecting mongoose to my local MongoDB server

Hello Everyone! Currently, I am in the process of linking my node.js project to mongodb. Initially, everything worked smoothly when I used mongodb atlas. However, when I attempted to connect it using mongodb compass, I faced some issues and nothing seemed ...

Encountering an Angular 13 ChunkLoadError during application deployment, despite the presence of the respective chunk

We encountered an issue with our application's upgrade from Angular 11 to 13. While running 'ng serve' on the local machine works fine, deploying it to our Azure app service causes the lazy loaded modules to fail loading. The specific error ...

What steps can I take to avoid an invalid operation on a potentially null reference in typescript?

Take a look at this scenario where the variable a can potentially be null, and is explicitly defined as such. Even when strict null checks are enabled, TypeScript does not flag a possible issue in this situation - let a: string | null = "hello" function ...

Retrieve the most recent information based on the ID from an object by utilizing timestamps within Angular 6

I have an array of objects stored in the 'component' variable component=[{id:1,date:'20-10-2020'},{id:1,date:'13-01-2020'},{id:2,date:'30-03-2020'}] Within this array, there are 2 objects with the same 'id&apos ...

Angular ensures that the fixed display element matches the size of its neighboring sibling

I have a unique challenge where I want to fix a div to the bottom of the screen, but its width should always match the content it scrolls past. Visualize the scenario in this image: The issue arises when setting the div's width as a percentage of the ...

TS2304: 'Omit' is a mysterious being that cannot be located

Encountered an issue while compiling my Angular project. This is a project that has remained unchanged for some time and is built daily by Jenkins. However, today it started failing and I'm struggling to determine the cause. ERROR in [at-loader] ./no ...

Properties of a child class are unable to be set from the constructor of the parent class

In my current Next.js project, I am utilizing the following code snippet and experiencing an issue where only n1 is logged: class A { // A: Model constructor(source){ Object.keys(source) .forEach(key => { if(!this[key]){ ...

Do you think this is a clever way to circumvent using ENUM for a parameter?

As I continue to explore different coding styles in Typescript and Angular, I recently encountered a method without any comments attached to it. It seems like this method is enforcing that the value passed in must be one of the defined options, but strang ...

Unable to subscribe due to the return value being an AnonymousSubject rather than an Observable

I am facing an issue in Angular 4 where I am attempting to retrieve details from a specific user when clicking on the 'user link profile'. However, I am unable to subscribe to my function because the return value of switchMap is AnonymousSubject ...