0

I'm trying to figure how to make a option selected when displayed, using old javascript style code or other language I would place a for example :

<select>
for (x =0 ; x < elements.size ; x++) {
<option value="element.id" if (element.id == selected.id ) print selected (endif)>element.name</option>
}
</select>

Trying to do this in angularjs I ended up with something like shown bellow.

This is the code:

import { Component } from '@angular/core';

export class Category {
    id: number;
    name: String;
    parent_id: number;
}

const CATEGORIES: Category[] = [
    {id: 1, name: "Calças", parent_id: 0},
    {id: 2, name: "Calças de ganga", parent_id: 1},
    {id: 3, name: "Calças Moleton", parent_id: 1},
    {id: 4, name: "T-shirt", parent_id: 0},
    {id: 5, name: "Casaco", parent_id: 0},
    {id: 6, name: "Casaco Moleton", parent_id: 5},
    {id: 7, name: "Sapato", parent_id: 0},
    {id: 8, name: "Ténis", parent_id: 7},
    {id: 9, name: "Sapato senhora", parent_id: 7},
    {id: 10, name: "Cintos", parent_id: 0},
];

@Component({
  template: `
  This is the category page.
  Procurar:&nbsp;<input type="text" name="search" />
  <button >Procurar</button>

  <table class="table table-bordered table-hover">
    <tr>
    <th>Id</th>
    <th>Nome</th>
    <th>Categoria Pai</th>
    </tr>
    <tr *ngFor="let cat of categories" (click)="onSelect(cat)">
        <td>{{cat.id}}</td>
        <td><input type="text" value="{{cat.name}}" /></td>
        <td>
            <select>
            <option value="0">&nbsp;</option>
                <option *ngFor="let parent of categories" 
                value="{{parent.id}}">
                    {{parent.name}}
                </option>
            </select>
        </td>
    </tr>
    </table>

  `
})

export class CategoryComponent  { 
    categories = CATEGORIES;

    parents : Category[];

    selectedCategory: Category;

    onSelect(cat: Category): void {
        this.selectedCategory = cat;
    }

    parentCategories() : Category[] {
        var parents : Category[];
        for (let cat of this.categories ) {
            if (cat.parent_id == 0 ) {
                parents.push(cat);
            }
        }
        return parents;
    }
}

How can I do this correctly?

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
Fernando André
  • 1,213
  • 3
  • 19
  • 32

1 Answers1

3

Add [(ngModel)]="selectedValue" to your select? Quoting the angular docs:

<select class="form-control"  id="power"
      required
      [(ngModel)]="model.power" name="power">
  <option *ngFor="let pow of powers" [value]="pow">{{pow}}</option>
</select>
meriton
  • 68,356
  • 14
  • 108
  • 175