Search code examples
angularangular-pipe

Custom pipe to templateUrl


I have created a custom pipe.

import { Component, Pipe,PipeTransform} from '@angular/core';

@Component({
  selector: 'app-summary',
  templateUrl: './summary.component.html',
  styleUrls: ['./summary.component.css']
})

@Pipe({
    name:'summary'
})
export class SummaryComponent implements PipeTransform {

  transform(value:string,args?:any) {
   // details
}

In my app.component.html. I have

 <app-summary></app-summary>  

And in my summary.component.html, I have

<input type="text" [(ngModel)]="title" >
<br>
{{title}}

I want to use the pipe in {{title}}. But it seems that the pipe is not applied. What I am missing?

EDIT: I added the pipe code details.

import { Component, Pipe,PipeTransform} from '@angular/core';

@Component({
   selector: 'app-summary',
   templateUrl: './summary.component.html',
   styleUrls: ['./summary.component.css']
})

@Pipe({
    name:'summary'
})
export class SummaryComponent implements PipeTransform {

  transform(value:string,args?:any) {
       if(!value)
          return null;
          let prep = ['of','the'];
       let splitted = value.split(' '); 

       for(var i=0;i<splitted.length;i++){
           if(i>0 && prep.includes(splitted[i].toLowerCase()))
              splitted[i]=splitted[i].toLowerCase();
           else
           {
            splitted[i]= splitted[i].substring(0,1).toUpperCase()+splitted[i].substring(1).toLowerCase();
           }
       }
       return splitted.join(' ');
  }
}

Solution

  • This is the correct way to implement a pipe:

    summary.pipe.ts

    import { Pipe,PipeTransform} from '@angular/core';
    
    @Pipe({
        name:'summary'
    })
    export class SummaryPipe implements PipeTransform {
    
      transform(value:string,args?:any) {
        // details
      }
    }
    

    summary.component.ts

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-summary',
      templateUrl: './summary.component.html',
      styleUrls: ['./summary.component.css']
    })
    export class SummaryComponent {
    
    }
    

    Then you can use the pipe in your view like this:

    <input type="text" [(ngModel)]="title" >
    <br>
    {{title | summary }}
    

    Don't forget to add the SummaryPipe in the NgModule in which you want to use it:

    @NgModule({
      declarations: [
        SummaryComponent,
        SummaryPipe
      ],
      providers: [...]
    })
    export class SummaryModule { }