7

I have an array as collection and I want to load it within dropdown list & I want a default selection on some condition but I don't know how to achieve this.

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-commingsoon',
  templateUrl: './commingsoon.component.html',
  styleUrls: ['./commingsoon.component.css']
})
export class CommingsoonComponent implements OnInit {
  public collection = [];
  constructor() {
    for(let i = 1; i<=10 ; i++) {
      this.collection.push(`Angular: ${i}`);
    }
   }

  ngOnInit() {
  }

}

app.component.html

<select name="" id="" style="position:relative; left: 100px">
    <option *ngFor="let i of collection;" value="{{i}}" [selected]="i == Angular: 2">{{ i }}</option>
</select>

I want the drop down should be selected value of when i == Angular: 2

1
  • 5
    quotes are missing, try i == 'Angular: 2'. Commented Nov 12, 2018 at 7:22

2 Answers 2

13

Here is a typical way of using ngModel This is more convenient if you are going to process selected value afterwards.

<select [(ngModel)]="selectedValue">
  <option *ngFor="let option of options" [value]="option.id">
    {{option.name}}
  </option>
</select>

https://stackblitz.com/edit/angular-njs3tz

Sign up to request clarification or add additional context in comments.

Comments

7

Quotes are missing, please try i == 'Angular: 2'

Or, if you are just interested in the index:

<option *ngFor="let i of collection; let j = idx" value="{{i}}" [selected]="j === 2">{{ i }}</option>

2 Comments

@AbhayjeetSingh please mark it as the answer, thanks.
This really should be the selected answer, fits the use case I was looking for perfectly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.