Categories
Angular Answers

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

Spread the love

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

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *