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
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.
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.
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With