I need to prepopulate the first value of the options drop-down menu with the value of a variable when loading a component. (This value comes from a db, but to simplify everything I have populated it manually.) The options are loaded dynamically with an ngFor cycling through an array. I would like the first option to be the value of firstColor.
Here is a stackbliz with the code example.
Component:
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"
}
];
}
}
Template
<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>