My Angular 5 Pipe "trim" is not getting called, why?
11,757
You're only using the pipe on an empty string when bg.name is falsy. Fix by moving parentheses:
<span>{{(bg.name ? bg.name + ', ' : '') | trim}}</span>
By the way, you'd gain performance benefits if you moved the entire logic to a pipe or pre-formatted the string before passing it to a template (ie. in component or service code). Angular runs all evaluations in template interpolations on every change detection cycle, while pure pipes are cached until the input value changes.
Related videos on Youtube
Author by
Yashwardhan Pauranik
Updated on June 04, 2022Comments
-
Yashwardhan Pauranik almost 2 years
I've created an angular
Pipe
namedtrim
. This pipe is designed to remove the last character from the string. Here is my pipe classTrimPipe
. The console is not logging the values when the pipe is used inside the HTML. HTML usage here -<ng-container *ngFor="let bg of backgrounds.preferred"> <span>{{bg.name ? (bg.name + ', ') : '' | trim}}</span> </ng-container>
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'trim' }) export class TrimPipe implements PipeTransform { transform(value: any, args?: any): any { console.log(value, args, 'Pipes'); return value.toString().substring(0, value.length - 1); } }
My
app.module.ts
file -import {BrowserModule} from '@angular/platform-browser'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {HttpClientModule} from '@angular/common/http'; // Custom import {AppComponent} from './app.component'; import {CommonService} from './shared/services/common.service'; import {DirectivesModule} from './shared/directives/directives.module'; import {PipeModule} from './shared/pipe/pipe.module';] @NgModule({ declarations: [ AppComponent ], imports: [ DirectivesModule, PipeModule, HttpClientModule, BrowserModule, BrowserAnimationsModule, NgSelectModule, FormsModule ], providers: [CommonService], bootstrap: [AppComponent] }) export class AppModule { }
My
pipe.module.ts
-import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TrimPipe } from './trim.pipe'; @NgModule({ imports: [ CommonModule ], declarations: [TrimPipe], exports: [TrimPipe] }) export class PipeModule { }
-
Yashwardhan Pauranik about 6 yearsNow I can sleep in peace.... Thanks a lot man... such a silly mistake..
-
funkizer about 6 yearsJavascript engines will let you know of any uncaught errors u know :)
-
karora about 6 yearsYeah, I've had situations where they show up in unexpected places and it can be hard to track them through thirty-five layers of closures, so I tend to try and catch them as close to where they happen, if I feel it's appropriate.