Select default option value from typescript angular 6
Asked Answered
A

18

69

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 ?

Aldin answered 24/6, 2018 at 11:7 Comment(1)
Set nrSelect to the default value. By the way, if you want binding to work, you ned to change it to [(ngModel)] as wellKenny
R
69

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.

Reinforcement answered 24/6, 2018 at 11:40 Comment(0)
F
52

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
}
Flexure answered 24/6, 2018 at 11:12 Comment(0)
D
29

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>
Detection answered 24/4, 2019 at 20:9 Comment(1)
I tried this on Angular 11. Not working. I solved the issue by setting on the class side: this.form.setValue({fieldName: 47});Anticoagulant
S
11

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"];
Smattering answered 12/12, 2018 at 22:37 Comment(0)
H
9

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
          . . .
     });
  }
}
Haye answered 15/5, 2020 at 14:24 Comment(0)
C
8

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];
Chrysa answered 10/4, 2020 at 20:15 Comment(0)
B
7

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" 
}
Bluestocking answered 24/6, 2018 at 11:14 Comment(2)
You've typed nrSelect as a string, and used a number literal, so I don't think this would compileKenny
I'm using Angular 9 and that's actually the only way I've found it workingVlad
G
6

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>
Gleet answered 3/8, 2018 at 3:34 Comment(0)
H
5

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]
Haldane answered 28/5, 2019 at 16:36 Comment(1)
This works well but there is a small gotcha if you are not paying attention. Even though you did it here, it's not obvious that if the control is inside a form, you MUST include the name='something'. It won't work without it.Furtado
L
4

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>
Locoweed answered 3/6, 2019 at 8:12 Comment(0)
L
2
<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;
}
Lunneta answered 10/11, 2020 at 10:5 Comment(0)
I
2

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>
Illustrator answered 20/11, 2020 at 17:21 Comment(0)
T
1

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>
Trellas answered 31/10, 2020 at 20:25 Comment(0)
B
0

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.

Bunchy answered 5/5, 2020 at 10:39 Comment(0)
C
0

If you are using FormBuilder, you can also do this

In your component.html

<select formControlName="genero" id="genero" name="country" 
        class="form-control form-select" data-bs-placeholder="Género">
    <option value="F">Femenino</option>
    <option value="M">Masculino</option>
    <option value="O">Otro</option>
</select>

In your component.ts

formInfoAdmin = new FormGroup({
    genero: new FormControl('F'),
})

And your output would be

enter image description here

Connett answered 18/7, 2022 at 6:6 Comment(0)
R
0
<select [(ng-model)]='nrSelect' >                                                                
    <option [value]='47'>47</option>
    <option [value]='46'>46</option>
    <option [value]='45'>45</option>
</select>

Use square brackets for each option value


Raddi answered 5/12, 2022 at 8:50 Comment(0)
P
0

This seemed to work for me. Note the selected option looks back at the component properties and if the truthy validates, you get the proper selection.

<select class="form-select" (change)="changeLookBackPeriod($event)">
    <ng-container *ngFor="let time_series_period of time_series_periods">
      <option [value]="time_series_period" [selected]="(time_series_period == lookback_period)"> {{ time_series_period }}</option>
    </ng-container>
</select>
Plasia answered 2/7, 2023 at 0:47 Comment(0)
A
-1

In the component.html file, you can simple use [ngModel] to set the default value and create an option for that.

Ex.1: Static option values

<select [ngModel]="0" class="form-control">
    <option value='0'>Default</option>
    <option value='1'>Option 1</option>
    <option value='2'>Option 2</option>
</select>

Ex.2: Dynamic option values

<select [ngModel]="0" class="form-control">
    <option value='0'>Default</option>
    <option *ng-For="let item of list, let i = index"
        [value]='item.key'>
        {{item.value}}
    </option>
</select>
Anetta answered 16/9, 2022 at 18:32 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.