Using Pipes Replace String In Angular 7

Nay mình chia sẻ với mọi người cách dùng Pipes trong Angular 7, bạn có thể dùng cách này cho Angular nhỏ hơn, như Angular 2, thông thường thì khi ta làm một project website nào đó, thường có những từ hay những ký hiệu ta muốn nó replace thành một chuổi khác hoặc ký tự khác.

* Tạo project Angular

npm install -g @angular/cli
ng new my-app

Sau khi tạo project xong bạn tạo cho mình thư mục _pipes trong thư mục app và tạo file formatStringPipe.ts Như sau:

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


@Pipe({name: "formatString"})
export class FormatStringPipe implements PipeTransform {
    transform(value: string, args?: any[]): string {
      
        // For each argument

        for(var key in args) {
          value = value.replace("{{" + key + "}}", args[key])
        }
      
        return value;
    }
}

Trong file Pipes bên trên chúng ta để ý như sau: value là chuổi chúng ta đưa vào, args[] là một mạng các key từ khóa mà ta cần dò tìm và replace chúng, muốn sử dụng được pipes file vừa tạo , ta cần phải import file này vào app.module.ts nhé

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';


import { AppComponent } from './app.component';
import { FormatStringPipe } from './stringFormatPipe';

@NgModule({
  imports: [ BrowserModule  ],
  declarations: [ AppComponent, FormatStringPipe ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

File app.module.ts bên trên mình import file pipes vừa tạo vào, giờ các bạn muốn sử dụng chức năng pipes này như thế nào thì mình chỉ việc gọi nó trong component html của ta thôi.

Ví dụ như sau ở đây mình chuẩn bị sẵn bạn mở file app.component.ts lên và nhập thông tin như sau:

export class AppComponent{
    birthday = new Date(1988, 3, 15); // April 15, 1988
    myString = "{{xyz}} is car , mode {{date}}";
    myString2 = "vt  vt  vt";
    myString3 ='<div class="content"><p><strong>abc</strong> <strong>def</strong></p></div><br/><div class="content"><p><strong>abc</strong> <strong>def</strong></p></div>';
    myString4 = 'nm in Hoanguyenit, nm mode 2019';
    constructor(){

    }
}

Trong file app.component.ts trên mình khai báo một số chuỗi myString để hồi mình dùng pipes replace các chuổi ký tự mà mình khai báo trong app.component.html

<div class="row">
    <div class="col-md-4">
        <h2>Pipe in Angular</h2>
        <ol>
            <li>{{birthday | date}}</li>
            <li>{{birthday | date:"MM/dd/yy"}}</li>
            <li>{{  birthday | date:'fullDate' | uppercase}}</li>
            <li>{{ myString | formatString: { xyz: 'Atial V 2019', date: '2019' } }}</li>
            <li>{{ myString2 | formatString: { vt: 'Atial V 2019'} }}</li>
            <li>{{ myString3 | formatString: { abc: 'Angular 7',def:'HoanguyenIT'} }}</li>
            <li>{{ myString4 | formatString: { nm: 'Angular 7'} }}</li>
        </ol>
    </div>
</div>

Các bạn nhìn thấy bên trên mình dùng pipes để replace, mình khai báo một cái keyvalue cho vào một cái mảng args của bên pipes, để cho pipes nhận biết được cái chuổi value và mãng chứa các key cần replace

Giờ các bạn cần chỉnh lại file pipes mình vừa tạo hồi nảy như sau:

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


@Pipe({name: "formatString"})
export class FormatStringPipe implements PipeTransform {
    transform(value: string, args?: any[]): string {
       //replace myString
       for(var key in args) {
        value = value.replace("{{" + key + "}}", args[key])
        
      }

      //replace myString2
      var re = /vt/gi; 
      value = value.replace(re, args["vt"])


      //replace myString3
      var abc = /abc/gi;
      var def = /def/gi;
      value = value.replace(abc,args['abc']).replace(def,args["def"]);

       
        //replace myString4
        var expr = "nm";
        value = value.replace(new RegExp(expr, 'gi'), args["nm"]);
        

        return value;
    }
}

Trong file pipes bên trên mình khai báo nhận giá trị string và mãng args chứa các key bên app.component.html chuyền vào, sau đó mình chỉ việc xử lý thôi, ở đây mình làm ví dụ nên để chúng vào một file pipes, các bạn nên để nó tách riêng ra nếu project của bạn xử lý nhiều pipes , thì mình có thể tạo nhiều file trong thư mục _pipes của ta.

Hình ảnh minh họa:

Bạn có thể tìm hiểu thêm các pipes như sau:AsyncPipe, CurrencyPipe ,DatePipe, DecimalPipe, JsonPipe, PercentPipe, LowerCasePipe, UpperCasePipe, SlicePipe, TitleCasePipe

Bài Viết Liên Quan

Messsage

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)