我正在尝试计算如何在显示时选择一个选项,使用旧的javascript样式代码或我放置的其他语言 例如:
<select>
for (x =0 ; x < elements.size ; x++) {
<option value="element.id" if (element.id == selected.id ) print selected (endif)>element.name</option>
}
</select>
尝试在angularjs中做到这一点我最终得到了如下所示的东西。
这是代码:
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: <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"> </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;
}
}
我该如何正确地做到这一点?
答案 0 :(得分:3)
将[(ngModel)]="selectedValue"
添加到您的选择中?引用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>