I have a select html like this:
In case you use Angular's FormBuilder
this is the way to go (at least for Angular 9):
yourelement.component.html
Use [formGroup]
to reference form variable, and use formControlName
to reference form's inner variable (both defined in TypeScrit file). Preferably, use [value]
to reference some type of option ID.
<form [formGroup] = "uploadForm" (ngSubmit)="onSubmit()">
. . .html
<select class="form-control" formControlName="form_variable" required>
<option *ngFor="let elem of list" [value]="elem.id">{{elem.nanme}}</option>
</select>
. . .
</form>
yourelement.component.ts
In the initialization of FormBuilder
object, in ngOnInit()
function, set the default value you desire to be as default selected.
. . .
// Remember to add imports of "FormsModule" and "ReactiveFormsModule" to app.module.ts
import { FormBuilder, FormGroup } from '@angular/forms';
. . .
export class YourElementComponent implements OnInit {
// <form> variable
uploadForm: FormGroup;
constructor( private formBuilder: FormBuilder ){}
ngOnInit() {
this.uploadForm = this.formBuilder.group({
. . .
form_variable: ['0'], // <--- Here is the "value" ID of default selected
. . .
});
}
}
app.component.html
<select [(ngModel)]='nrSelect' class='form-control'>
<option value='47'>47</option>
<option value='46'>46</option>
<option value='45'>45</option>
</select>
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
nrSelect = 47
}
<select class="form-control" [value]="defaultSelectedCurrency" formControlName="currency">
<option *ngFor="let item of currency" [value]="item.value" [selected]="item.isSelected">{{item.key}}</option>
</select>
currency = [
{ key: 'USD', value: 'USD', isSelected: true },
{ key: 'AUD', value: 'AUD', isSelected: false }
];
defaultSelectedCurrency: string;
ngOnInit() {
this.defaultSelectedCurrency = this.currency[0].value;
}
I think the best way to do it to bind it with ngModel.
<select name="num" [(ngModel)]="number">
<option *ngFor="let n of numbers" [value]="n">{{n}}</option>
</select>
and in ts file add
number=47;
numbers=[45,46,47]
In addition to what mentioned before, you can use [attr.selected]
directive to select a specific option, as follows:
<select>
<option *ngFor="let program of programs" [attr.selected]="(member.programID == program.id)">
{{ program.name }}
</option>
</select>
<select class='form-control'>
<option *ngFor="let option of options"
[selected]="option === nrSelect"
[value]="option">
{{ option }}
</option>
</select>
nrSelect = 47;
options = [41, 42, 47, 48];