Reputation: 403
I am using angular5. I want to make a option selected as default. But when I use the ngModel directive my code does not work anymore.
here is my code:
<select class="form-control" [ngModelOptions]="{standalone: true}" [(ngModel)]="singleCar">
<option value="null" selected='true' disabled>select car </option>
<option [ngValue]="Car" *ngFor="let car of allCars">{{singleRole.name}}</option>
</select>
does someone have a solution?
thx guys!
Upvotes: 0
Views: 53
Reputation: 754
You have to do this in the html:
<option [ngValue]="null">Select a car</option>
and in your component, you have to specify that the default value is null.
This works:
singelCar = null;
This does not:
singleCar;
Upvotes: 1
Reputation: 1
Try removing the option value="null"
. As by default, the first option value is set.
Upvotes: 0
Reputation: 39482
There are some issues with the values and in some cases the directives
that you've used.
Give this a try in your Template:
<select
class="form-control"
[(ngModel)]="singleCar">
<option
value="null"
disabled>
Select A Car
</option>
<option
[value]="car"
*ngFor="let car of allCars">
{{car.name}}
</option>
</select>
And in your Component:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
singleCar = { name: 'Car 4' };
allCars = [
{ name: 'Car 1' },
{ name: 'Car 2' },
{ name: 'Car 3' },
{ name: 'Car 4' },
{ name: 'Car 5' },
];
}
Here's a Working Sample StackBlitz for your ref.
Upvotes: 0