I have a select html like this:
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"
}
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.
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.
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>
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>
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>