Pablo Aguirre de Souza
Pablo Aguirre de Souza

Reputation: 4149

Dynamic select without repeating value in angular

I created a dynamic select based in a value contained in an object fetched from a database. When I'm looping through the objects, how to avoid repetition of values?

This is the html

<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>

This is the ts

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)
      }
    )
  }
}

Stackblitz: https://stackblitz.com/edit/angular-6ni1pg

Upvotes: 1

Views: 61

Answers (1)

Vitalii Ilchenko
Vitalii Ilchenko

Reputation: 598

Data structure called Set will help you to get unique values: https://stackblitz.com/edit/angular-vdch68

// transactions.component.ts

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

Upvotes: 2

Related Questions