简体   繁体   中英

How to create a pipe to format account numbers?

Is there an expert in Angular, who can take the time to explain to me how one can create a pipe to format the account number?

The account number always has a mandatory length of 12 digits.

For example => 123456789123

  • The variable retrieved from the webService is of type number .

  • I would like to get this type of display

123-4567891-23
458-4698712-15
etc...

I'm still too beginner to figure out how I should create this. Would someone be kind enough to help me create the pipe, so I can understand.

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

@Pipe({
  name: 'accountDash'
})
export class AccountDashPipe implements PipeTransform {
  transform(): any {
    return;
  }
}

Thank you for your help, I apologize if my message is too light.

You can convert the number to a string and format it quite easily

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

@Pipe({
  name: 'accountDash'
})
export class AccountDashPipe implements PipeTransform {
  transform(accountNumber: Number): string {
    return String(accountNumber).replace(/^(\d{3})(\d{7})(\d{2})$/, `$1-$2-$3`)
  }
}

All you need to do is then apply it to your template.

<span>{{someAccountNumber|accountDash}}</span>

You may or may not want to add some error handling in the pipe to detect if it is attempting to consume an invalid account number.

StackBlitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM