0

I have a dynamic select but I don't know how to display the selected values on the view. I'm struggling because apparently I can't create a click event on the option and I don't know how to access the option via the click event on tag.

Here's the html:

<router-outlet></router-outlet>
<hr>
<div class="row">
  <div class="col-xs-12">
    <form [formGroup]="catSelection">
      <select 
      formControlName="transactionControl" 
      (change)="onDisplayCategory()">
    <option  [ngValue]="transactionCategory" *ngFor="let transactionCategory of transactionCategories">{{transactionCategory}}</option>
    </select>
    </form>
  </div>
<div></div>
</div>

Here's the ts

import { Component, OnInit } from '@angular/core';
import { DataFetchingService } from '../shared/data-fetching.service';
import { Transaction } from '../shared/transaction.model';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-transactions',
  templateUrl: './transactions.component.html',
  styleUrls: ['./transactions.component.css']
})
export class TransactionsComponent implements OnInit {
  result: Transaction[]
  transactions: Transaction[]
  transactionCategories: Set<string>
  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;
        this.transactionCategories = new Set<string>(posts.map(p => p.category))
        console.log(this.transactionCategories)
        console.log(this.transactions)
      }
    )
  }

  onDisplayCategory() {
    console.log("change works")
  }
}

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

3 Answers 3

1

You can use Angular's two-way binding for this.

Use [(ngModel)]="selectedCategory" on your select and then use selectedCategory in your ts file as a variable and you will have access to the option chosen. Then use your variable when an option is selected.

onDisplayCategory() {
  console.log("change works");
  console.log(this.selectedCategory)
}

I've modified your example, have a look: https://stackblitz.com/edit/angular-yx9jhq

Sign up to request clarification or add additional context in comments.

Comments

1

you can get your selected dropdown values as below one.

onDisplayCategory() { console.log("change works"); console.log(this.catSelection.value.transactionControl); }

Comments

1

You can use @Input and @Ouput to submit the selected value in the dropdown (in child transactions-edit.component.ts) and show it (in parent transactions.component.ts).

To do this, you would probably modify a little bit in your codes

Changes in transactions.component.html

<app-transactions-edit (createPostEvent)="onPostCreated($event)"></app-transactions-edit> <!-- change this line-->
<hr>
<div class="row">
  <div class="col-xs-12">
    <form [formGroup]="catSelection">
      <select 
        formControlName="transactionControl" 
        (change)="onDisplayCategory()">
    <option [ngValue]="transactionCategory" *ngFor="let transactionCategory of transactionCategories">{{transactionCategory}}</option>
    </select>
    </form>
  </div>
<div></div>
</div>

Add one more method in transactions.component.ts

onPostCreated(postData: Transaction) {
    console.log("onPostCreated", postData)
    this.catSelection.controls['transactionControl'].patchValue(postData.category)
}

Changes in transactions-edit.component.ts

import { Component, Input, Output, OnInit, EventEmitter } from '@angular/core';
import { DataStorageService } from '../../shared/data-storage.service';
import { Transaction } from '../../shared/transaction.model';


@Component({
  selector: 'app-transactions-edit',
  templateUrl: './transactions-edit.component.html',
  styleUrls: ['./transactions-edit.component.css']
})
export class TransactionsEditComponent implements OnInit {

  @Output() createPostEvent = new EventEmitter()

  constructor(private dsService: DataStorageService) { }

  ngOnInit() {
  }

  onCreatePost(postData: Transaction) {
    this.dsService
      .createAndStorePost(postData.name, postData.amount, postData.category)
      .subscribe(responseData => {
        console.log(postData)
        this.createPostEvent.emit(postData)
      })

  }
}

See the source at https://stackblitz.com/edit/angular-y3w7yv

7 Comments

Hey! Your example works fine on changing the value of the select. Which is super cool by the way. But my intention was to display the list based on the category chosen on select. Sorry if I wasn't clear. :)
Do you want to filter out the list of posts in budget-dfc78.firebaseio.com/posts.json where the category == selected category in the form?
Yes. The posts above told me how to grab the value of select. I also know how to filter the list "manually", just creating one array for each category. But if I have 1000 categories I need an elegant approach just filtering based on value of select.
I updated the code, can you check it out. Hope this helps you. stackblitz.com/edit/angular-y3w7yv
It is nice to get feedback from you @Pablo Aguirre de Souza if the latest update that satisfies you. Thanks.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.