0
votes

I'm a newbie in angular 4. I'm facing a problem with *ngFor with HTML drop-down select and option.

I have categories array-object -

categories = [
{ id:1, title: 'c/c++'},
{ id:2, title: 'JavaScript'},
{ id:3, title: 'Angular'},
{ id:4, title: 'Node'}
];

I want to show title in the dropdown but I want to get the category id in the ngModel.

Like - in HTML view show all title in a dropdown list, but when I select one of them then ngModel will get that category id.

i.e: I select JavaScript, ngModel will get the id of JavaScript category.

I search much time on google but I could not find any solution.

Here is HTML code -

  <label>Category</label>
  <select [(ngModel)]="post.category_id" class="form-control select2" style="width: 100%;">
      <option  *ngFor="let category of categories">{{ category.title}}</option>
   </select>
3

3 Answers

0
votes

You can bind the value property:

<option *ngFor="let category of categories" [value]="category.id">{{ category.title }}</option>
0
votes

You will have to update ngModel variable and option as below.

<select [(ngModel)]="category_id" class="form-control select2">
   <option *ngFor="let category of categories" [value]="category.id" 
           [innerHtml]=" category.title "></option>
</select>

In your code post.category_id post will get the value of id and then post.category_id will give undefined.

0
votes

After various tries able to find out the mistake you are making..... Please check the following points first

  • First of all to include the ngModel directive you have to import the following in your app.ts:

 import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
  • After importing these your @NgModule must look like this

    @NgModule({

  imports: [ BrowserModule,FormsModule,
    HttpModule ],
  declarations: [ App ],
  bootstrap: [ App ]
  })
  • After this try this code to check for the desired result

 <label>Category</label>
      <select [(ngModel)]="category_id" name="category_id" class="form-control select2" style="width:100%">
      <option *ngFor="let category of categories" [value]="category.id">{{ category.title }}</option>
      </select>
      <h2>Select Category Id : {{category_id}}</h2>

You must get your desired result after these steps