簡體   English   中英

Angular2插值不會在更改時更新

[英]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放在類方法或組件方法中,則會得到相同的結果:

<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];
  }
}

檢查撥栓

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM