Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select default option value from typescript angular 6

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 ?

like image 242
bramzoti Avatar asked Jun 24 '18 11:06

bramzoti


People also ask

How do I set the default option in select?

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.

How do I set default selected value in ng-options?

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 the selector option does in angular?

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.


3 Answers

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.

like image 90
Shadab Faiz Avatar answered Sep 19 '22 05:09

Shadab Faiz


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
}
like image 44
Fartab Avatar answered Sep 20 '22 05:09

Fartab


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>
like image 20
katwhocodes Avatar answered Sep 23 '22 05:09

katwhocodes