Reputation: 165
I need to set a default value/placheholder in my select option, it looks easy to do but I wasn't able to do it. I've tried different things but I got the same result.
<select class="form-control border custom-select" [compareWith]="compareFn"
[(ngModel)]="skill.category">
<option selected disabled="disabled">Chose a category...</option>
<option *ngFor="let cat of categories" [ngValue]="cat"
[hidden]="cat.id === 1">{{cat.name}}</option>
</select>
compareFn(c1: Skill, c2: Skill): boolean {
return c1 && c2 ? c1.id === c2.id : c1 === c2;
}
My output is something like this:
[CATEGORY id=1] default //I want this to be totaly hidden (id=1 hidden)
dropdown {
[Chose a category...]
[CATEGORY id=2]
[CATEGORY id=3]
[CATEGORY id=4]
... } end dropdown
Upvotes: 0
Views: 322
Reputation: 335
in template you can in many ways, one more is:
<select class="form-control border custom-select" [compareWith]="compareFn"
[(ngModel)]="skill.category">
<mat-label>Chose a category...</mat-label>
<ng-container *ngFor="let cat of categories" >
<option *ngIf="cat.id !== 1" [ngValue]="cat">{{cat.name}}</option>
</ng-container>
</select>
use mat-label if the value od the disabled option is not a valid option, the user must not be able to select a not valid option do you really need the value of the selected to be the entire object? or better removing before template
http.get<cat[]>('url').pipe(
map(list => list.filter(one => one.id !== 1))
).subs...
or even better removing from query in the database
Upvotes: 1
Reputation: 10975
To achieve expected result, use slice pipe
<select class="form-control border custom-select">
<option selected disabled="disabled">Chose a category...</option>
<option *ngFor="let cat of categories| slice:1" [ngValue]="cat">
{{cat.name}}</option>
</select>
code reference - https://stackblitz.com/edit/angular-ay8zzk
Please refer this link for more details on Slice Pipe - https://angular.io/api/common/SlicePipe
Upvotes: 1
Reputation: 3763
I'd suggest not sending down the result for ID: 1 as you will not be utilizing it. Component would be something like:
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
title = "CodeSandbox";
category = 0;
categories = [
{ id: 2, name: "Opel" },
{ id: 3, name: "Mazda" },
{ id: 4, name: "BMW" }
];
}
Template:
<select class="form-control border custom-select" [(ngModel)]="category">
<option selected disabled="disabled" [value]="0">Chose a category...</option>
<option *ngFor="let cat of categories" [value]="cat.id">{{cat.name}}</option>
</select>
Upvotes: 0