【问题标题】:Angular2 Interpolation doesn't update on changeAngular2插值不会在更改时更新
【发布时间】:2016-07-25 09:15:04
【问题描述】:

在此模板中:

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

生产:

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

【问题讨论】:

    标签: angular angularjs-interpolate


    【解决方案1】:

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

    尝试以下方法:

    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

    【讨论】:

    • 太棒了!谢谢。我想了解更多关于 + 在 value 参数中的作用,以及这两个选项中哪一个更高效。如果您有时间,我将不胜感激。
    • 参见文档developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。我认为第二个选项性能更高,但速度差异几乎察觉不到
    • 我通读了一遍,起初不明白为什么我需要将条件值转换为数字。我四处打听,得知&lt;input&gt; 总是产生一个字符串,所以需要+ 运算符将字符串转换为数字。
    猜你喜欢
    • 1970-01-01
    • 2023-03-28
    • 2016-08-08
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多