Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular preselect select option

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>
like image 226
michelemalagnini Avatar asked Oct 18 '25 06:10

michelemalagnini


1 Answers

Try something like this:

<select name="colors" id="colors">
  <option *ngFor="let c of colors" [ngValue]="c" [selected]="c.name === this.firstColor[0].name" >
    {{c.code}}
  </option>
</select>

You can also change firstColor from array of objects to just object, and then the solution would be:

<select name="colors" id="colors">
  <option *ngFor="let c of colors" [ngValue]="c" [selected]="c.name === this.firstColor.name" >
    {{c.code}}
  </option>
</select>
like image 99
Pawel Avatar answered Oct 19 '25 22:10

Pawel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!