Trying to understand how to preselect an option when displayed, I attempted it with old JavaScript style code or another language. 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>
After attempting this in AngularJS, my code ended up looking like the following.
Here is the modified code snippet:
import { Component } from '@angular/core';
export class Category {
id: number;
name: String;
parent_id: number;
}
const CATEGORIES: Category[] = [
{id: 1, name: "Pants", parent_id: 0},
{id: 2, name: "Jeans", parent_id: 1},
// more categories here...
];
@Component({
template: `
This is the category page.
Search: <input type="text" name="search" />
<button >Search</button>
<table class="table table-bordered table-hover">
<tr>
<th>Id</th>
<th>Name</th>
<th>Parent Category</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"> </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 properly accomplish this task?