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?
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" />
Can someone explain why it has to be split out like this? I am trying to bind a date to an input with type date: [(ngModel)]="model.endDate | date:'y-MM-dd'" and the pipe will not work. However, if I do away with the banana syntax and use the split out syntax above it works fine.
Did this really work? it didn't work for me. it says Cannot have a pipe in an action expression
This worked for me to! @BlakeRivell "[]" binds the property one-way from data source to view target at that point you can change how it is displayed with a pipe. When using the "()" binding it is the other way around changing the format would be useless here. So I guess thats why the banana's in a box "[()]" don't work with a pipe and splitting them is the way to go. You can read more about it here: angular.io/docs/ts/latest/guide/…
Beware that in the example the pipe only works to one direction. Let's say
item.value
is a number, and you useDatePipe
to convert it into a date string. When the date is edited, the$event
will also be a date string and will not fit back intoitem.value
You have to reverse what the pipe did in your(ngModelChange)
expression - i.e. turn the date string back to a number.@Protagonist
(ngModelChange)="updateItemValue($event)"
, then create anupdateItemValue(date: string)
method and inside ititem.value = someConversionFunction(date);
Now if you're asking what should you use as the conversion function, I don't know. MaybeDate.parse()
might work.