【问题标题】:How to show the data filter by regular expression in Angular 7如何在Angular 7中通过正则表达式显示数据过滤器
【发布时间】:2019-05-15 15:31:24
【问题描述】:

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

配置.json

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

samplepage.component.html

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

sample.component.ts

this.sampledata= "123456789321";

我希望输出为 123-456789-321

我试过这样用

{{样本数据 |过滤器:myregExp}}

不起作用。有人能帮助我吗。我是 Angular/javascript 的新手。

【问题讨论】:

标签: angular typescript


【解决方案1】:

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

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

所以在本例中 AppModule.ts 的代码如下所示:

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 中使用如下:

{{ your_value | customPipe}}

WORKING_DEMO

【讨论】:

  • var disco = this.AddDashes(value, 3, 6).join('-') 在这一行中,第 3 行和第 6 行是静态的。我不能用这个。我的正则表达式可以是任何东西,自定义管道应该灵活匹配任何正则表达式。
  • @rakesh 我认为您不能使用正则表达式修改字符串!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 1970-01-01
  • 2021-07-11
  • 1970-01-01
  • 1970-01-01
  • 2012-11-15
相关资源
最近更新 更多