2016-07-25 29 views
1

更新此模板:Angular2插不上變化

<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語句?

回答

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

+0

太棒了!謝謝。我想了解更多關於值參數中「+」的含義,以及這兩個選項中哪一個更高性能。如果你有一分鐘​​,我會欣賞一些指針。 –

+0

請參閱文檔https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus。我認爲第二個選項是更高性能的,但速度差異幾乎察覺不到 – yurzui

+0

我讀過,並開始不明白爲什麼我需要將條件值轉換爲數字。我問周圍,並得知''總是產生一個字符串,所以需要'+'運算符將字符串轉換爲數字。 –