How to set default value selected if i use ngModel, ngValue and how to add placeholder in select
<select [(ngModel)]="defaultSelect" (change)="onChangeGoods(query_param)" #query_param="ngModel" name="query_param" >
<option [ngValue]="{'sortBy': 'price', 'sortOrder': 'asc'}" > От дешевых к дорогим</option>
<option [ngValue]="{'sortBy':'price', 'sortOrder':'desc'}" > От дорогих к дешевым</option>
<option [ngValue]="{'sortBy':'rating', 'sortOrder':'desc'}" > По рейтингу</option>
</select>
<select [(ngModel)]="goods_for_brands[i]" (change)="onChangeBrand(brand)" #brand="ngModel" name="brand" id="brand" >
<option [ngValue] = "" selected >choose BRAND</option>
<option [ngValue]="good.brand" *ngFor="let good of goods_for_brands">{{good.brand}}</option>
</select>
CodePudding user response:
If you want a default value, you only need init the value with a init value.
<select [(ngModel)]="select" (ngModelChange)="onChangeGoods($event)" [compareWith]="compareFn">
<option value="" disabled>Choose a state</option>
<option [ngValue]="{ sortBy: 'price', sortOrder: 'asc' }">A</option>
<option [ngValue]="{ sortBy: 'price', sortOrder: 'desc' }">B</option>
<option [ngValue]="{ sortBy: 'rating', sortOrder: 'desc' }">C</option>
</select>
ts
export class AppComponent {
name = 'Angular ' VERSION.major;
select = { sortBy: 'price', sortOrder: 'asc' };
onChangeGoods(optionsValue: any) {}
compareFn(c1: any, c2: any): boolean {
return c1 && c2 ? c1.sortBy === c2.sortBy && c1.sortOrder === c2.sortOrder : c1 === c2;
}
}
You can see I init the prop named select
with a default value. Notice the compareFn
function, your value is a object, so you should write a compare function and bind it to your select.
[compareWith]="compareFn"
You can see a demo below:
https://stackblitz.com/edit/angular-ivy-8gsw9a?file=src/app/app.component.ts