如果我使用 ngModel、ngValue 以及如何在 select 中添加占位符,如何设置默认值 selected

How to set default value selected if i use ngModel, ngValue and how to add placeholder in select

如果我使用 ngModel、ngValue 如何设置默认值 selected 以及如何在 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>

如果你想要一个默认值,你只需要用一个初始值来初始化这个值。

<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;
    }
}

你可以看到我用默认值初始化了名为 select 的道具。注意 compareFn 函数,你的值是一个对象,所以你应该写一个比较函数并将它绑定到你的 select.

[compareWith]="compareFn"

您可以在下面观看演示:
https://stackblitz.com/edit/angular-ivy-8gsw9a?file=src/app/app.component.ts