2017-03-22 119 views
1

我正在嘗試自定義管道:Angular 2自定義管道無法讀取null屬性

從'@ angular/core'導入{Pipe,PipeTransform};

@Pipe({ 
    name: 'doubleNumber' 
}) 
export class DoubleNumberPipe implements PipeTransform { 

    transform(value: any, ...args: any[]): any { 
    if(value == null) 
    { 
     return null; 
    } 
    else{ 
     return value*2; 
    } 
    } 

} 

我宣佈它在app.module.ts聲明裝飾部分:

declarations: [ 
AppComponent, 
DataDrivenComponent, 
DoubleNumberPipe 

],

然後,我創建了一個HTML表單採取數量和一倍:

<div class="container"> 
    <div class="row"> 
    <div class="col-md-6 col-md-offset-3"> 
    <p>Number</p> 
    <input type="text" #val (keyup)="0"> 
    <p>{{val.value | doubleNumber}}</p> 
    <hr> 
     <h1>Forms</h1> 
     <hr> 
    </div> 
    </div> 
</div> 

結果僅爲「0」,並且出現以下錯誤:

EXCEPTION: Error in ./DataDrivenComponent class DataDrivenComponent - inline template:37:54 caused by: Cannot read property 'value' of null ErrorHandler.handleError @ error_handler.js:54 (anonymous) @ application_ref.js:261 ZoneDelegate.invoke @ zone.js:334 onInvoke @ ng_zone.js:273 ZoneDelegate.invoke @ zone.js:333 Zone.run @ zone.js:126 (anonymous) @ zone.js:713 ZoneDelegate.invokeTask @ zone.js:367 onInvokeTask @ ng_zone.js:264 ZoneDelegate.invokeTask @ zone.js:366 Zone.runTask @ zone.js:166 drainMicroTaskQueue @ zone.js:546

和:

Unhandled Promise rejection: Error in ./DataDrivenComponent class DataDrivenComponent - inline template:37:54 caused by: Cannot read property 'value' of null ; Zone: ; Task: Promise.then ;

+1

試試這個'VAL .value',並顯示您的組件 –

+0

都能跟得上的代碼?它沒有與貓王運營商 – droidnation

回答

2

正如mickdev建議......幾乎是正確的,但是您會得到NaN錯誤,因爲您已將輸入類型定義爲text

<input type="text" [(ngModel)]="val"> 
<p *ngIf="val">{{val | doubleNumber}}</p> 

刪除,或type="number"替換:

<input [(ngModel)]="val"> 
<p *ngIf="val">{{val | doubleNumber}}</p> 
+0

Plunker:http://plnkr.co/edit/EIlXULYxz8lVBwyEHK2n?p=preview – Alex

+0

它在plnkr鏈接上工作,但仍然有相同的錯誤。我會設置這個答案是正確的,但仍然有相同的問題 – droidnation

+0

你可以用你的代碼,例如我的蹲跳者叉,我很樂意看看它:) – Alex

1

嘗試elvis operator這樣:

<p>{{val?.value | doubleNumber}}</p> 
+0

合作。它沒有與貓王運營商 – droidnation

+0

一起工作,仍然是相同的錯誤? –

+0

不幸的是。仍然是一樣的 – droidnation

1

你應該在這種情況下使用ngModel。這樣的事情:

<input type="text" [(ngModel)]="val"> 
<p *ngIf="val">{{val | doubleNumber}}</p> 

無需使用鍵控,這將自動更新您的VAL。

+0

仍然是一樣的錯誤,但結果NaN – droidnation

+0

看到我更新的答案。我在條件塊中封裝了'val',所以只有當用戶提供一個值時纔會評估它。 – mickdev

相關問題