How do i select the first option in a select by default in angular 2 the following code don\'t seems to work.
You can select first option by default using index value.
<select id="sType" class="form-control" [(ngModel)]="params.searchType">
<option *ngFor="let t of sTypes; let i = index" [attr.value]="t.value" [attr.selected]="i == 0 ? true : null">{{t.name}}</option>
</select>
1) I hope this approach can help as well!
<select id="category" name="category" class="form-control" formControlName="category">
<option [attr.selected]="true" [ngValue]="categories[0].id" >{{categories[0].name}}</option>
<option *ngFor="let cat of categories.slice(1)" [ngValue]="cat.id">{{cat.name}}</option>
</select>
2 ) If you are using a Form control you need just to set it like default value
this.fgAddingProduct = new FormGroup({
category: new FormControl(this.categories[0].id, [Validators.required]),
});
And use a normal *ngFor
<select id="category" name="category" class="form-control" formControlName="category">
<option *ngFor="let cat of categories" [ngValue]="cat.id">{{cat.name}}</option>
</select>
If you use Model Driven Forms you can set the selected default value of your <select>
in your component (ngOnInit()
)
componenet.file.ts
public fieldSelect : any;
ngOnInit(){
...
this.fieldSelect= { key: "mySelect", label: "Example Select"};
this.controlsConfig= [];
this.controlsConfig[this.fieldSelect.key] = [""];
this.myFormGroup= this.formBuilder.group(this.controlsConfig);
...
}
component.file.html
<div class="col-md-2" [formGroup]="myFormGroup">
<select (change)="onChangeTypeImp($event)" [formControlName]="fieldSelect.key">
<option *ngFor="let item of items;" [value]="item">{{item}}</option>
</select>
</div>
Model-Driven Forms: While using directives in our templates gives us the power of rapid prototyping without too much boilerplate, we are restricted in what we can do. Reactive forms on the other hand, lets us define our form through code and gives us much more flexibility and control over data validation.+
There is a little bit of magic in its simplicity at first, but after you're comfortable with the basics, learning its building blocks will allow you to handle more complex use cases.
[example]
Or simply like this :)
<option *ngFor="let value of values; let i = index"
[ngValue]="value"
[attr.selected]="!i"
>{{item}}</option>
Enjoy !