Select default option value from typescript angular 6

AngularTypescriptDropdown

Angular Problem Overview


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 ?

Angular Solutions


Solution 1 - Angular

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.

Solution 2 - Angular

> 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
}

Solution 3 - Angular

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>

Solution 4 - Angular

Correct Way would be :

<select id="select-type-basic" [(ngModel)]="status">
    <option *ngFor="let status_item of status_values">
    {{status_item}}
    </option>
</select>

Value Should be avoided inside option if the value is to be dynamic,since that will set the default value of the 'Select field'. Default Selection should be binded with [(ngModel)] and Options should be declared likewise.

status : any = "47";
status_values: any = ["45", "46", "47"];

Solution 5 - Angular

First or all you are using ng-model which is considered to be an angularjs syntax. Use [(ngModel)] instead with the default value

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:string = "47" 
}

Solution 6 - Angular

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]

Solution 7 - Angular

HTML

<select class='form-control'>
    <option *ngFor="let option of options"
    [selected]="option === nrSelect"
    [value]="option">
        {{ option }}
    </option>
</select>

Typescript

nrSelect = 47;
options = [41, 42, 47, 48];

Solution 8 - Angular

In case you use Angular's FormBuilder this is the way to go (at least for Angular 9):

HTML view: 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>
Logic file: yourelement.component.ts

In the initialization of FormBuilderobject, 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
          . . .
     });
  }
}

Solution 9 - Angular

I had similar issues with Angular6 . After going through many posts. I had to import FormsModule as below in app.module.ts .

import {FormsModule} from '@angular/forms';

Then my ngModel tag worked . Please try this.

<select [(ngModel)]='nrSelect' class='form-control'>                                                                
                                <option [ngValue]='47'>47</option>
                                    <option [ngValue]='46'>46</option>
                                    <option [ngValue]='45'>45</option>
</select>

Solution 10 - Angular

i manage this by doing like this =>

<select class="form-control" 
        [(ngModel)]="currentUserID"
        formControlName="users">
        <option value='-1'>{{"select a user" | translate}}</option>
            <option 
            *ngFor="let user of users"
            value="{{user.id}}">
            {{user.firstname}}
   </option>
</select>

Solution 11 - Angular

<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;
}

Solution 12 - Angular

You may use bellow like in angular 9

 <select [(ngModel)]="itemId"  formControlName="itemId" class="form-control" >
          <option [ngValue]="" disabled>Choose Gender</option>             
          <option *ngFor="let item of items"  [ngValue]="item .id" [selected]="item .id == this.id"  >
             {{item.name}}
          </option>
   </select>

Solution 13 - Angular

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>

Solution 14 - Angular

In my case I'm using the same markup for editing an existing entity, or creating a brand new one (so far anyway).

I want to display a default-value that is "selected" in the select-elements when in creationMode, while displaying the values form the backend in editMode.

My solution is:

<select [(ngModel)]="entity.property" id="property" name="property" required>
  <option disabled hidden value="undefined">Enter prop</option>
  <option *ngFor="let prop of sortedProps" value="{{prop.value}}">{{prop.displayName}}</option>
</select>

for the regular available options I'm using a sortedProps Array to provide option choices. But that's not the important part here.

What did the trick for me is setting value="undefined" to let the angular-model-binding (?) select this option automatically when in creationMode. Not sure if its a hack, but does exactly what i want. No addtionally typeScript necessary.

Additionally, sepcifing hidden makes sure the option in my case is not selectable, while required makes sure the form is invalid unless something gets selected there.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbramzotiView Question on Stackoverflow
Solution 1 - AngularShadab FaizView Answer on Stackoverflow
Solution 2 - AngularFartabView Answer on Stackoverflow
Solution 3 - AngularkatwhocodesView Answer on Stackoverflow
Solution 4 - AngularSaumyajitView Answer on Stackoverflow
Solution 5 - AngularSajeetharanView Answer on Stackoverflow
Solution 6 - Angularuser9292877View Answer on Stackoverflow
Solution 7 - AngularMatheen U KView Answer on Stackoverflow
Solution 8 - AngularSergioView Answer on Stackoverflow
Solution 9 - AngularRavishankar TiruamalasettiView Answer on Stackoverflow
Solution 10 - AngularAbdelwahed HouboubyView Answer on Stackoverflow
Solution 11 - AngularSan JaisyView Answer on Stackoverflow
Solution 12 - AngularEnamul HaqueView Answer on Stackoverflow
Solution 13 - Angularuser11006614View Answer on Stackoverflow
Solution 14 - AngularicyerasorView Answer on Stackoverflow