user10102331
user10102331

Reputation:

I need to send values from my select options

I am using angular I want to send information about what element I selected in the select option. Specifically I want to send the data-value to a variable in my product-form.component.ts. I tried using ngModel but I keep getting errors saying that it doesn't recognize (click)=selectCategory1(category) use a function I am using template forms for my forms that could be the reason. You can see my code live at : https://stackblitz.com/github/RashellSmith/Dashboard-FrontEnd

Product Form component html

<div class="form-group">
    <label for="productCategory">Product Category</label>
    <select  [(ngModel)]="model.category" (click)=selectCategory1(category) name="category"  class="form-control" id="productCategory" (click)="value()">
        <option *ngFor="let category of categories" (click)=selectCategory1(category) data-value="{{category.category}}" id={{category.categoryName}} >{{category.categoryName}}</option>
    </select>
</div>

Product Form component ts

export class ProductFormComponent implements OnInit {

suppliers: Supplier[];
categories: Category[];
value: number;

model = new Newproduct("name",new Category( this.value,"name"),66,33,true,new Supplier(null,null),76);
selectCategory1(Category){
  console.log(Category);
}
submitted = false;
get diagnostic() { return JSON.stringify(this.model); }

onSubmit() { this.submitted = true; }

  constructor(private supplierService: SupplierService,private categoryService: CategoryService) { }

  ngOnInit() {
    this.supplierService.getAll().subscribe(data => {
      this.suppliers = data;
    });

    this.categoryService.getAll().subscribe(data => {
      this.categories = data;
    });
  }
}

Upvotes: 1

Views: 55

Answers (1)

Saksham
Saksham

Reputation: 9380

You are definitely trying to over-complicate things. You need to bind a simple (change) method to your select list which would be be triggered on value change. You can either pass the value to this function using template reference variable as

<Select #select (change)="SelectChanged(select.value)">

Or you can bind [(ngModel)] directive and access that directly in your component class on (change)

A sample template code:

<select [(ngModel)]="selectedOption" (change)="GetSelectedValue(selectedOption)">
    <option *ngFor="let option of options" [ngValue]="option">{{option}}</option>
</select>

And component class would look like

GetSelectedValue(val) {
    //do something with val
}

Stackblitz at: https://stackblitz.com/edit/angular-r4d7ul

Upvotes: 1

Related Questions