Bind and select dropdown value in typescript and Angular2

This question has been asked many times and couldn't help me with my problem. Not sure what happened to the approach and hope that fresh "eyes"

Here is my dropdownlist binding in HTML: I am binding programname, which is a string for both values ​​and text properties.

<select [ngModel]="selectedObject">
   <option *ngFor="let p of programs" value= {{p.programName}}>
         {{p.programName}}
   </option>
</select>

      

In my .ts file, this is what I do to bind the default to "select"

 loadData(pList: IProgram[]) {
    this.programs = pList;
    if (this.programs.length > 0) {
        this.selectedObject = this.programs[0];
    }
}

      

The data binds to "select" correctly,

  • but the default is shown as empty text where i need to click and select the value.
  • Another problem is that when I change the dropdown value from A to B, the "selectedObject" value always gives me "A" instead of "B". Since this is [ngModel], two-way binding is taken care of. But, this does not happen as I may have missed something here.

Can anyone help with this issue?

0


source to share


2 answers


try below,

<select [(ngModel)]="selectedObject">
   <option *ngFor="let p of programs" 
           [ngValue] = "p"
           [selected]="p.programName == selectedObject.programName"
          >
         {{p.programName}}
   </option>
</select>

      



Check out Plunker !!

Hope this helps!

0


source


Basically the problem is with the [ngModel] declaration. It should be within the [(ngModel)], which was missed in my original problem. :)

Many thanks to Madhu Ranjan for helping me fix it!



After a fix (ngModel) able to bind and retrieve successfully.

<select [**(ngModel)**]="selectedObject"><option *ngFor="let p of programs"value= {{p.programName}}>{{p.programName}}</option> </select>

0


source







All Articles