如何在Angular 7中通过正则表达式显示数据过滤器 [英] How to show the data filter by regular expression in Angular 7

查看:63
本文介绍了如何在Angular 7中通过正则表达式显示数据过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事Angular 7项目.我有一个Config.json,它具有一些正则表达式,如下所示.我有一些静态数据要过滤并显示以匹配正则表达式.

I am working on Angular 7 project. I have a Config.json which has some regular expression as shown below. I have some static data which i want to filter and show to match regular expression.

Config.json

Config.json

{
"myregExp" : "[0-9],\\d,\\d,-,[0-9],\\d,\\d,\\d,\\d,\\d,-,[0-9],\\d,\\d"
}

samplepage.component.html

samplepage.component.html

<h1>{{sampledata}}</h1>

sample.component.ts

sample.component.ts

this.sampledata= "123456789321";

我希望输出为123-456789-321

I want the output as 123-456789-321

我试图这样使用

{{sampledata |filter:myregExp}}

无法正常工作.有谁可以帮助我吗.我是angular/javascript的新手.

I tried to use like this

{{sampledata | filter : myregExp}}

which is not working. Can someone help me please. I am new to angular/javascript.

推荐答案

您可以通过创建自定义管道"来实现.

You can achieve that by creating Custom Pipe.

创建管道并将其添加到AppModule中的 declarations 数组中:

Create Pipe and Add it in AppModule inside declarations array:

因此,在这种情况下,AppModule.ts代码如下:

So in this case AppModule.ts Code looks like:

import { CustomPipePipe } from './app/custom-pipe.pipe';

@NgModule({
  ......
  ......
  declarations: [CustomPipePipe],
  ......
})

自定义管道代码:

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

@Pipe({
  name: 'customPipe'
})
export class CustomPipePipe implements PipeTransform {

  transform(value: any, args?: any): any {
    var disco = this.AddDashes(value, 3, 6).join('-')
    console.log(disco)
    return disco;
  }


  AddDashes(str, firstGroup, SecondGroup) {
    var response = [];
    var isSecondValue = false;

    for (var i = 0; i < str.length; i += firstGroup) {
      if (!isSecondValue) {
        firstGroup = 3;
        response.push(str.substr(i, firstGroup));
        isSecondValue = true;
      }
      else {
        response.push(str.substr(i, SecondGroup));
        isSecondValue = false;
      }
    }
    return response
  };
}

并以类似HTML的格式使用它:

And use it in HTML Like:

{{ your_value | customPipe}}

WORKING_DEMO

这篇关于如何在Angular 7中通过正则表达式显示数据过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆