Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set select option value to null in Angular 2

I have the following markup:

<select [ngModel]="selectedCategory" 
     (ngModelChange)="selectCategory($event && $event != 'null' ? $event : null)">

  <option [value]="null">(all categories)</option>
  <option *ngFor="let cat of categories" [ngValue]="cat">{{cat.name}}</option>

</select>

and in TypeScript:

export class MyComp {
    public categories: Category[];
    public selectedCategory: Category;
    public selectCategory(cat: Category) {
        this.selectedCategory = cat;
        doStuff();
    }
}

It just doesn't look like the correct way to do it. Is there any other less verbose way to get a default option with a value of null (not 'null')? I can't put the default option in the categories array since it would mess up other code. And I don't mind the ngModelChange since I need to run custom code on selection. It's just the $event && $event != 'null' ? $event: null part I would like to clean up.

I can't use [ngValue] on the default options; it just gives me a value of 0: null (string). And skip setting value results in binding selectedCategory=null not to match the default option leaving the combo box unselected at init.

like image 591
maloo Avatar asked May 15 '16 19:05

maloo


1 Answers

While Igors solution isn't working quite right for me, here's what I use:

<select [ngModel]="selectedItem" (ngModelChange)="selectItem($event)">
    <option [ngValue]="null">Don't show</option>
    <option *ngFor="let item of items" [ngValue]="item">{{item.text}}</option>
</select>
import { Component, Input } from '@angular/core';
@Component()
export class SelectionComponent {
    @Input() items: any[];
    selectedItem: any = null;
    selectItem(item?: any)
    {
        // ...
    }
}

There's two important details to consider here:

  1. In the template, make your default option use null as ngModel, like this: [ngValue]="null". This is to bind a null option.
  2. Make sure to assign the selectedItem in the component null, otherwise it's undefined and your select will show as empty / not have the default selection.
like image 188
GeorgDangl Avatar answered Sep 30 '22 16:09

GeorgDangl