I have a select html like this:
<select ng-model='nrSelect' class='form-control'>
<option value='47'>47</option>
<option value='46'>46</option>
<option value='45'>45</option>
</select>
How can I select the default value from typescript for example 47 ?
The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.
In my opinion the correct way to set a default value is to simply pre-fill your ng-model property with the value selected from your ng-options , angular does the rest. Essentially when you define the $scope property your select will bind to assign it the default value from your data array.
What is a Selector in Angular? A selector is one of the properties of the object that we use along with the component configuration. A selector is used to identify each component uniquely into the component tree, and it also defines how the current component is represented in the HTML DOM.
You can do this:
<select class='form-control' (change)="ChangingValue($event)" [value]='46'> <option value='47'>47</option> <option value='46'>46</option> <option value='45'>45</option> </select> // Note: You can set the value of select only from options tag. In the above example, you cannot set the value of select to anything other than 45, 46, 47.
Here, you can ply with this.
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
}
For reactive form, I managed to make it work by using the following example (47 can be replaced with other value or variable):
<div [formGroup]="form">
<select formControlName="fieldName">
<option
*ngFor="let option of options; index as i"
[selected]="option === 47"
>
{{ option }}
</option>
</select>
</div>
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