Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make dropdown list selected with loop in angular 6?

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

like image 287
Abhayjeet Singh Avatar asked Nov 12 '18 07:11

Abhayjeet Singh


People also ask

How do I get the value of the selected dropdown menu item with angular?

Using NgModel Directive Angular has another way to get the selected value in the dropdown using the power of ngModel and two-way data binding. The ngModel is part of the forms module. We need to import it into the NgModule list in the app. module , which will be available in our app.

How do you display a selected value in a drop-down list?

Method 1: Using the value property: The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.


2 Answers

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

like image 108
Icycool Avatar answered Oct 30 '22 05:10

Icycool


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>

like image 7
Boland Avatar answered Oct 30 '22 05:10

Boland