bellotas
bellotas

Reputation: 2471

Setting value of Select - Angular 2

I have to set the option value of my select using a JSON file. The Object is the following:

export class Car {
  ID: String;
  Name: [{
    confName: String
    }
  }]
}

I am trying to set it with the following code:

this.baseService.getCars(message)
    .subscribe(cars => {
    this.cars = cars;
    myCars = this.cars; //Car is a global variable
    });

var $el = $("#carSelect");
$el.empty(); // remove old options
$.each(myCars, function (key, value) {
$el.append($("<option></option>")
    .attr("value", value).text(key));
});

I know that for accessing to the confName of one of them I need to use console.log(myCars[0].Name.confName); so probably the error is here:

 $.each(myCars

because I need to access to Name to get then the value,key of confName I want to do it for each each

Upvotes: 0

Views: 51

Answers (1)

user4676340
user4676340

Reputation:

Stop using JQuery !

This is counter productive : you're using an advanced platform that can ease your life so much, yet you install another library to do exactly what it is supposed to do.

Not only you load unnecessary code, but it slows down your application and forces other devs to have knowledge about JQuery.

You want to give your select a value ? Here is how to do it in Angular.

First, create your select and options, and bind a value to it.

<select [(ngModel)]="mySelect">
  <option *ngFor="let opt of myOptions" [value]="opt">{{ opt}}</option>
</select>

Then, create the variables in your TS, and set the value of your select in your constructor.

export class myComponent {
  mySelect: string;
  myOptions: ['option 1', 'option 2', 'option 3'];
  constructor() {
    this.mySelect = this.myOptions[0];
  }
}

Your select now has the value of your first option.

If you want to use a service, do it like this

export class myComponent {
  mySelect: string;
  myOptions: ['option 1', 'option 2', 'option 3'];
  constructor() {
    this.loadCars();
  }
  loadCars() {
    this.baseService.getCars(message)
      .subscribe(cars => {
        this.myOptions= cars;
        this.mySelect= cars[0];
    });
  }
}

EDIT If you want to use objects :

<select [(ngModel)]="mySelect">
  <option *ngFor="let opt of myOptions" [value]="opt.value">{{ opt.desc }}</option>
</select>

In your TS

myOptions: [
  { value: 1, desc: 'option 1' },
  { value: 2, desc: 'option 2' },
  { value: 3, desc: 'option 3' },
];

Upvotes: 2

Related Questions