2
Create a PIPE via command CLI Angular:
ng g pipe CPF
after this command will be created a file with the name of cpf.pipe.ts
that its value (value
) with a regular expression can create the CPF mask of the as follows:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'CPF'
})
export class CPFPipe implements PipeTransform {
transform(value: string, ...args: any[]): any {
if (value.length === 11) {
return value.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/g, '\$1.\$2.\$3\-\$4');
}
return 'error';
}
}
To use this pipe
must be registered on app.module.ts
in the array
declarations
, example:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CPFPipe } from './cpf.pipe';
@NgModule({
declarations: [AppComponent, CPFPipe],
imports: [BrowserModule, AppRoutingModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
After this setting just use
{{ numero_cpf | CPF }}
References
Has there been any response?
– novic
@Virgilionovic is receiving this message after implementing his solution: Uncaught Error: Template parse errors: The pipe 'CPF' could not be found ("="user.sex==1">Male</td> <td *ngIf="user.sex==2">Female</td> <td>{{[ERROR ->]user.Cpf | CPF}}</td> <td>{user.nationality}}</td> <td>{user.naturalness"): ng:///Appmodule/Userlistcomponent.html@25:18 at syntaxError (Compiler.js:2175)
– alexjosesilva
@Virgilionovic the mistake was the name of the pipe...had put into minuscule.
– alexjosesilva