user12466101
user12466101

Reputation: 17

How to Pass a Dropdown value in Angular to a Function?

I have a dropdown value that is correctly displayed in the UI with the below:

<select [(ngModel)]="ccodeSelect" (ngModelChange)="ccodeSelect($event)">
  <option type="number" value=0>--Select a Company Code--</option>
  <option type="number" *ngFor="let dropdown of listDropdown" [value]="dropdown.Ccode">{{dropdown.Ccode}}</option>
  </select>

It is as well correctly displayed in my visual selection below:

<h6>Company Code: {{ccodeSelect}}</h6>

My question is how to make sure the dropdown value is taken in my function when I click Submit? This is my submit button function:

createBilling(billing: Billing) {
return this.httpconnect.post(`${this.PATH}/billing`,billing);}

I need to basically replace the value in my function for ccode by the dropdown value

I am adding my Interface too where you can see the ccode value I am trying to replace:

 export interface Billing {
id?: number;
ccode?: number;
customer?: number;

};

Any idea? Thanks

Upvotes: 0

Views: 1700

Answers (3)

Sadegh
Sadegh

Reputation: 107

billing.component.ts

@Component({
    ...
})
export class BillingComponent {
  ...
  billing: Billing = {};
    
  ...
    
  createBilling() {
    console.log(this.billing);
    return this.httpconnect.post(`${this.PATH}/billing`, this.billing);
  }
    
}

billing.component.html

<select [(ngModel)]="billing.ccode">
  <option type="number" value="0">--Select a Company Code--</option>
  <option type="number" *ngFor="let dropdown of listDropdown" [value]="dropdown.Ccode">
    {{dropdown.Ccode}}
  </option>
</select>

<button (click)="createBilling()">Create Billing</button>

Upvotes: 0

dom.macs
dom.macs

Reputation: 796

Remove the ngModelChange in your html.

<select [(ngModel)]="ccodeSelect">
  <option type="number" value=0>--Select a Company Code--</option>
  <option type="number" *ngFor="let dropdown of listDropdown" [value]="dropdown.Ccode">{{dropdown.Ccode}}</option>
</select>

Then update your submit function to assign the value of ccodeSelect to your billing object.

createBilling(billing: Billing) {
    billing.ccode = this.ccodeSelect;
    return this.httpconnect.post(`${this.PATH}/billing`, billing);
}

Upvotes: 1

Sanjay Jagad
Sanjay Jagad

Reputation: 41

Use (change) event instead of (ngModelChange).

in HTML:

     <select
        #mySelect
        (change)='onOptionChange(mySelect.value)'>
         <option *ngFor="let dropdown of listDropdown" 
           [value]="dropdown.Ccode">{{dropdown.Ccode}}
         </option>
    </select>

in TypeScript:

    onOptionChange(value:string){
     // you will get value here
     console.log("value is :: ", value);
    }

Upvotes: 2

Related Questions