angularpipehtml-inputangular2-ngmodel

Using Pipes within ngModel on INPUT Elements in Angular


I've an HTML INPUT field.

<input 
    [(ngModel)]="item.value" 
    name="inputField" 
    type="text" 
/>

and I want to format its value and use an existing pipe:

.... 
[(ngModel)]="item.value | useMyPipeToFormatThatValue" 
....

and get the error message:

Cannot have a pipe in an action expression

How can I use pipes in this context?


Solution

  • You can't use Template expression operators(pipe, save navigator) within template statement:

    (ngModelChange)="Template statements"
    

    (ngModelChange)="item.value | useMyPipeToFormatThatValue=$event"

    https://angular.io/guide/template-syntax#template-statements

    Like template expressions, template statements use a language that looks like JavaScript. The template statement parser differs from the template expression parser and specifically supports both basic assignment (=) and chaining expressions (with ; or ,).

    However, certain JavaScript syntax is not allowed:

    • new
    • increment and decrement operators, ++ and --
    • operator assignment, such as += and -=
    • the bitwise operators | and &
    • the template expression operators

    So you should write it as follows:

    <input [ngModel]="item.value | useMyPipeToFormatThatValue" 
          (ngModelChange)="item.value=$event" name="inputField" type="text" />
    

    Plunker Example