我需要在加载组件时使用变量值预填充选项下拉菜单的第一个值。 (此值来自数据库,但为了简化我手动填充的所有内容。)这些选项是动态加载的,ngFor
循环遍历数组。我希望第一个选项是 firstColor
的值。
Here is a stackbliz with the code example.
组件:
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"
}
];
}
}
模板
<h1>primo esempio</h1>
<label for="cars">Choose a car: </label>
<select name="cars" id="cars">
<option value="volvo">volvo</option>
<option value="saab">saab</option>
<option value="mercedes">mercedes</option>
<option value="audi">audi</option>
</select>
<h1>secondo esempio</h1>
<label for="cars">Choose a color: </label>
<select name="colors" id="colors">
<option *ngFor="let c of colors" [ngValue]="c">
{{c.code}}
</option>
</select>
最佳答案
尝试这样的事情:
<select name="colors" id="colors">
<option *ngFor="let c of colors" [ngValue]="c" [selected]="c.name === this.firstColor[0].name" >
{{c.code}}
</option>
</select>
您还可以将 firstColor
从对象数组更改为仅对象,然后解决方案将是:
<select name="colors" id="colors">
<option *ngFor="let c of colors" [ngValue]="c" [selected]="c.name === this.firstColor.name" >
{{c.code}}
</option>
</select>
关于 Angular 预选选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65107097/