Search code examples
javascriptangularangular-ngmodelsubjectsubject-observer

select on change angular implementation?


angularjs has a built in directive called onchanges which would listen to changes in a select or whatever and allow you to execute a function upon a change.

How I wish this was so in angular. Currently I am better understanding ngmodel and seeing how I might be able to use a subject to acheive the following.

I have a select of cities:

<div id="venueFilterParams" ngModelGroup="venueFilterParams">
          <!-- need to add default values from url-->
          <select [ngModel]="citySelect"
                  name="citySelect"
                  id="citySelect"
                  class="form-control">
            <option *ngFor="let city of cities" value="{{city}}">{{city}}</option> <!--come back and wire up-->
          </select>

and a select of neighborhoods:

 <select [ngModel]="neighborhoodSelected"
                  name="neighborhood"
                  id="neighborhood"
                  class="form-control">
            <option *ngFor="let neighborhood of neighborhoodlist" value="{{neighborhood}}">{{neighborhood}}</option>
          </select>

If the user selects a city other than the one passed in the URL leading to this page, (which will be default selected I have yet to build that yet)

I need my app to reach out to my database and repopulate the neighborhood select options with the neighboorhoods for that city.

All of that I can do fine, what I am trying to figure out is code which will listen to the city select and run a function which does the above.

Now [ngModel] = citySelect; will not on its own update, I have to wait for a submit click to capture the value but what about [(ngModel)] = citySelect and listening to the citySelect variable in a subject?

I'm going to keep working on this but your suggestions are really appreciated!


Solution

  • Angular has similar directives called (change) or (ngModelChange).

    You need two-way data binding if you want to set initial value for the city based on url. For two-way data binding, (ngModelChange) is a way to go.

    Therefore, in your city select:

    <select [ngModel]="citySelect"
        (ngModelChange)="onCityChange($event)"
        name="citySelect"
        id="citySelect"
        class="form-control">
      <option *ngFor="let city of cities" [value]="{{city}}">{{city}}
      </option> <!--come back and wire up-->
    </select>
    

    Then, define onCityChange in your component:

    public onCityChange(chosenCity) {
      console.log(chosenCity);
      // populate neighborhoodlist based on chosenCity
    }