Search code examples
angularselect2-way-object-databinding

Angular 2, setting the selected value on a select list based on selected value of another select list


I am sure this is a simple answer but I just cannot seem to solve it.

I have a dropdown list with names in it John, Jack, Jill, etc. I have a second List with professions in Builder, Joiner, Plasterer, etc.

What I am trying to do is when I select John, I know based on his data he is a Builder, so in my second list I want to change the selected value from "select" to "Builder".

Below is a plunker with what I currently have, any advise on how to make this would would be great.

enter link description here

This is my change method for my first dropdown but I am not getting the desired result:

     firstDropDownChanged(val: any) {
    console.log(val);

    if (val.profession == "Builder") {
      this._values2.selected = "Builder";
    }
    else if (val.profession == "Plumber") {
      this._values2.selected = "Plumber";
    }
    else if (val.profession == "Plasterer") {
      this._values2.selected ="Plasterer";
    }
   else if (val.profession == "Joiner") {
      this._values2.selected ="Joiner";
    }

Thanks Andy


Solution

  • If you don't actually need the variable selectedProfession easiest way would be to in the first dropdown we have the complete object, so that we can use it in the second dropdown. This way we need no methods. So the first one would look like this:

    <select [(ngModel)]="tradesman">
      <option>Select</option>
      <option [ngValue]="v" *ngFor='let v of _tradesmen'>{{ v.name }}</option>
    </select>
    

    where we use [ngValue] to bind the whole object, the second one would then look like:

    <select [(ngModel)]="tradesman.qualifications">
      <option>Select</option>
      <option *ngFor='let v of _qualifications'>{{ v.qualifications }}</option>
    </select>
    

    This way is also good if you want to capture any possible change in the qualifications, the tradesman variable will have the change.

    Here's demo: http://plnkr.co/edit/TFXUtezSuJsJVuHNXfQ3?p=preview