Angular2 Interpolation 不会根据变化更新

Angular2 Interpolation doesn't update on change

在此模板中:

<label for="condition">Condition</label>
<input type="range" min="0" max="4" name="condition"
        [(ngModel)]="vehicle.condition">
<span>{{vehicle.condition | condition}}</span>

我正在通过自定义管道插入范围滑块的数字输出,该管道应该将数值转换为人类可读的字符串:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'condition',
  pure: false
})
export class ConditionPipe implements PipeTransform {

  transform(value: number): any {
    switch (value) {
      case 0: return 'Damaged';
      case 1: return 'Rough';
      case 2: return 'Average';
      case 3: return 'Clean';
      case 4: return 'Outstanding';
    }

  }

}

使用这个管道,我只得到 vehicle.condition 初始值的正确输出。一旦我更新模型(通过拖动滑块),插值就会消失。从插值表达式中删除管道按预期工作,我看到数值在变化时更新。

如果我将此 switch 放入 class 方法或组件方法中,我会得到相同的结果:

<label for="condition">Condition</label>
<input type="range" min="0" max="4" name="condition"
       [(ngModel)]="vehicle.condition">
<p>numeric: {{vehicle.condition}}</p>
<p>pipe: {{vehicle.condition | condition}}</p>
<p>class method: {{vehicle.niceCondition(vehicle.condition)}}</p>
<p>component method: {{niceCondition(vehicle.condition)}}</p>

产生:

为什么使用此 switch 语句处理时插值不更新?

这是因为您正在尝试将字符串变量与数字进行比较。

尝试以下操作:

transform(value: number): any {
  switch (+value) { <== notice + before of value
    case 0: return 'Damaged';
    case 1: return 'Rough';
    case 2: return 'Average';
    case 3: return 'Clean';
    case 4: return 'Outstanding';
  }
}

或者你可以像这样改变你的管道:

@Pipe({
  name: 'condition',
  pure: false
})
export class ConditionPipe implements PipeTransform {
  result = {
    0: 'Damaged',
    1: 'Rough',
    2: 'Average',
    3: 'Clean',
    4: 'Outstanding'
  }
  transform(value: number): any {
    return this.result[value];
  }
}

勾选plunker