Angular 角度预选选项
加载组件时,我需要用变量值预填充选项下拉菜单的第一个值。(该值来自db,但为了简化我手动填充的所有内容。)通过Angular 角度预选选项,angular,select,option,Angular,Select,Option,加载组件时,我需要用变量值预填充选项下拉菜单的第一个值。(该值来自db,但为了简化我手动填充的所有内容。)通过ngFor循环数组动态加载选项。我希望第一个选项是firstColor的值 组成部分: import { Component, VERSION } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html&
ngFor
循环数组动态加载选项。我希望第一个选项是firstColor
的值
组成部分:
import { Component, VERSION } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
name = "Angular " + VERSION.major;
firstCar: String = "";
colors: any[] = [];
firstColor: any[] = [];
ngOnInit() {
this.firstCar = "audi";
this.firstColor = [
{
name: "bianco",
code: "#ffffff"
}
];
this.colors = [
{
name: "rosso",
code: "#ff0000"
},
{
name: "bianco",
code: "#ffffff"
},
{
name: "nero",
code: "#000000"
}
];
}
}
模板
primo-esempio
选择一辆车:
沃尔沃汽车
萨博
梅赛德斯
奥迪
第二埃森皮奥酒店
选择一种颜色:
{{c.code}}
尝试以下方法:
<select name="colors" id="colors">
<option *ngFor="let c of colors" [ngValue]="c" [selected]="c.name === this.firstColor[0].name" >
{{c.code}}
</option>
</select>
{{color['code']}
<select name="colors" id="colors">
<option *ngFor="let c of colors" [ngValue]="c" [selected]="c.name === this.firstColor.name" >
{{c.code}}
</option>
</select>
<select name="colors" id="colors">
<option *ngFor="let color of colors" [selected]="color['name'] === this.firstColor[0]['name']" >
{{color['code']}}
</option>
</select>