Warm tip: This article is reproduced from stackoverflow.com, please click
angular pipe html-input angular2-ngmodel

Using Pipes within ngModel on INPUT Elements in Angular

发布于 2020-04-13 10:22:55

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?

Questioner
Lonely
Viewed
563
yurzui 2018-06-08 19:09

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