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.
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:
null as ngModel, like this: [ngValue]="null". This is to bind a null option.selectedItem in the component null, otherwise it's undefined and your select will show as empty / not have the default selection.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With