Search code examples
angularcomboboxkendo-ui

Pass an html ngModel value to service angular


I want to pass an html ngModel value <kendo-dropdownlist style=" width: 92%;" [data]="year" [(ngModel)]="selectedYear"> which is located on Combocomponent.html, to a service which is called Home.service.ts.

Inside the service I have this code:

  configUrl1 = 'https://localhost:44361/api/Active_Serviced_Outlets?Year=2021&quarter=1&month=1';
  getMethod1() {
    
    return this.http.get(this.configUrl1);
  }  

I want to dynamically pass the [(ngModel)]="selectedYear" value to selected Year so every time the user inputs an year.

ComboComponent.html

<div class="row">
  <div class="column">

    <p> &nbsp; &nbsp;<b>Year </b></p>

    <kendo-dropdownlist [data]="year" [(ngModel)]="selectedYear"></kendo-dropdownlist>
  </div>
  <div class="column">

    <p> &nbsp; &nbsp;<b>Month</b></p>
    <kendo-dropdownlist [data]="Month" [(ngModel)]="selectedMonth"> </kendo-dropdownlist>
  </div>
  <div class="columnA">
    <p> &nbsp; &nbsp;<b>Quarter</b></p>
    <kendo-dropdownlist style=" width: 92%;" [data]="Quarter" [(ngModel)]="selectedQuarter"> </kendo-dropdownlist>
  </div>

   
</div>
<br />
<!--<div class="example-config">
  &nbsp; &nbsp;Selected Values: {{selectedYear}} &nbsp; &nbsp; {{selectedMonth}} &nbsp; &nbsp; {{selectedQuarter}}
</div>-->

Thank you!


Solution

  • You just need to a that selectedYear to your service.

    service.ts

    public selectedYear = 1900; // You can default to any year or make it null.
    
    
    getWhatever() {
      
      const url = `https://example/api/whatever?Year=${selectedYear}`
      return this.http.get(url);
    }  
    

    Then in the component, wrap the selectedYear in a getter and setter.

    component.ts

    public get selectedYear() {
      return this._service.selectedYear;
    }
    public set selectedYear(year: number) {
      this._service.selectedYear = year;
    }
    
    constructor(
      private readonly _service: myService
    ){}
    
    

    Finally, use the getter/setter in the HMTL. component.html

    <select [(ngModel)]="selectedYear">
    ...
    </select>
    

    Here is the demo.