Angular2插值在更改

时间:2016-07-25 09:15:04

标签: angular angularjs-interpolate

在此模板中:

<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放在类方法或组件方法中,我会得到相同的结果:

<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>

产地:

animation detailing unexpected interpolation behaviour

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

1 个答案:

答案 0 :(得分:2)

这是因为你试图将字符串变量与数字进行比较。

尝试以下方法:

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