Menu Close

How to use pipes within ngModel on input elements in Angular?

Sometimes, we want to use pipes within ngModel on input elements in Angular.

In this article, we’ll look at how to use pipes within ngModel on input elements in Angular.

How to use pipes within ngModel on input elements in Angular?

To use pipes within ngModel on input elements in Angular, we can use separate [(ngModel)] into [ngModel] and (ngModelChange).

For instance, we write

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

to apply the useMyPipeToFormatThatValue pipe to item.value in ngModel.

Then we handle our input change events in ngModelChange.

This is because we can’t use template expression operators in template statements, which are directives that are wrapped in parentheses.

Conclusion

To use pipes within ngModel on input elements in Angular, we can use separate [(ngModel)] into [ngModel] and (ngModelChange).

Posted in Angular, Angular Answers