S.A.R.A.
S.A.R.A.

Reputation: 165

How to set a Placeholder in Select/Option with NgModel in Angular2 (7)?

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:

Upvotes: 0

Views: 322

Answers (3)

Lean Pilar
Lean Pilar

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

Naga Sai A
Naga Sai A

Reputation: 10975

To achieve expected result, use slice pipe

  1. slice: 1 - if the value to be removed is always first option

<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

Rossco
Rossco

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

Related Questions