1
votes

I am trying to do a custom pipe:

import { Pipe, PipeTransform } from '@angular/core';

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

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

}

And I declared it in the declaration decorator section at the app.module.ts:

declarations: [
AppComponent,
DataDrivenComponent,
DoubleNumberPipe

],

Then I created an HTML form to take a number and double it:

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

The result was only "0" on the page, and the following error:

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

And:

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

3
try this val?.value, and show the code of your component - El houcine bougarfaoui
Nope. It didn't worked with the elvis operator - alim1990

3 Answers

2
votes

As mickdev suggested... is almost correct, but you get NaN error, because you have defined the input type as text.

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

Remove that, or replace with type="number":

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

Try elvis operator in this way:

<p>{{val?.value | doubleNumber}}</p>
1
votes

You should use ngModel in that case. Something like this :

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

No need to use keyup, this will auto update your val.