Enable Loose coupling in Angular using Pipes

Table of contents

With applications complexity increases, thus the code complexity too. To achieve a minimal coupling, we can process a function as Pipe in Angular and achieve the same.

Consider the following example of attaching the text to the input provided.

this.heightofPerson = data.heightInput + 'CM';

HTML part will look like,

<div>
    <span> The height of the person is {{heightofPerson}}
    </span>
</div>

Here the variable heightOfPerson is tightly coupled with the string CM and it should be appended every time and should be re-written again when used somewhere. To avoid this, Pipes can be used.

Pipes:

Pipes are similar to functions which get the value, process them and return the same to the called method. But this can be achieved more independently in Pipes.

import {Pipe, PipeTransform} from '@angular/core';
@Pipe ({name:'heightPipe'})
export class stringAttachPipe implements PipeTransform {        
      transform(height: number):string {
       return height +'CM';
    }
}

The corresponding HTML part can be viewed as,

<span> The height of the person is 
{{heightofPerson | heightPipe : heightInput }} </span>

Here, the height has been passed as an argument to the pipe. Thus pipe helps in reduced coupling.