如何在Angular 2中将select选项值设置为null

mal*_*loo 9 angular2-template angular

我有以下标记:

<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>
Run Code Online (Sandbox Code Playgroud)

在TypeScript中:

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

它看起来不像是正确的方法.是否有任何其他不那么冗长的方法来获取值为null(而不是'null')的默认选项?我不能将默认选项放在categories数组中,因为它会搞乱其他代码.我不介意ngModelChange因为我需要在选择时运行自定义代码.这只是$event && $event != 'null' ? $event: null我想清理的部分.

我无法使用[ngValue]默认选项; 它只给了我一个值0: null(字符串).并且跳过设置值导致绑定selectedCategory=null不匹配默认选项,而在init处取消选择组合框.

Geo*_*ngl 12

虽然Igors解决方案不适合我,但我使用的是:

<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>
Run Code Online (Sandbox Code Playgroud)
import { Component, Input } from '@angular/core';
@Component()
export class SelectionComponent {
    @Input() items: any[];
    selectedItem: any = null;
    selectItem(item?: any)
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

这里有两个重要的细节需要考虑:

  1. 在模板中,让你的默认选项使用null的ngModel,是这样的:[ngValue]="null".这是绑定null选项.
  2. 确保selectedItem在组件中分配null,否则它是未定义的,您select将显示为空/没有默认选择.


Igo*_*gor 6

截至目前,github 存储库中存在一个未解决的问题。

我发现这可以用来实现与您相同的功能,但代码稍微少一些。它还假设您没有使用空字符串作为可能的值,但如果您只是稍微修改它以在条件语句中考虑到这一点。

看法

<select [ngModel]="selectedCategory" 
        (ngModelChange)="selectedCategory = $event ? $event : null">
  <option value="">(all categories)</option>
  <option *ngFor="let cat of categories" [ngValue]="cat">{{cat.name}}</option>
</select>
Run Code Online (Sandbox Code Playgroud)

组件不需要额外的逻辑

export class MyComp {
    public categories: Category[];
    public selectedCategory: Category;
}
Run Code Online (Sandbox Code Playgroud)

如果您仍然想do stuff(参考您的代码示例)更改模型,那么您所拥有的方法会更适合,但如果您想要做的只是将值设置为有效类别,或者null如果没有选择任何单个类别,则这将使得代码更少。