Home > OS >  Angular: custom pipe for change text
Angular: custom pipe for change text

Time:06-03

I have a function that Random a number between 1 and 20.

The task I want to perform: When an elevator is in a lobby, use a custom pipe to display the word lobby instead of the number 1.

func in the service:

getNumbersInfinite(){
    return interval(1000).pipe(map(()=> Math.floor(Math.random() * 20)   1));
  }

in the component:

floor?: Observable<Number>;
  constructor(private randomNumberGen: RandomNumberGeneratorService) { }

  ngOnInit(): void {
    this.floor = this.randomNumberGen.getNumbersInfinite();
  }

html:

<div >
<pre >{{this.floor | async}}</pre>
</div>

CodePudding user response:

First, create the pipe replaceWordLoby.pipe.ts DOC

@Pipe({
    name: "replaceWordLoby",
})
export class ReplaceWordLobyPipe implements PipeTransform {
    transform(value: Number, ...args: unknown[]): string {
        // return word lobby 
    }
}

then import the class into the declarations array in your.module.ts file

@NgModule({
    declarations: [ReplaceWordLobyPipe],
})
export class YourModule {}

Now you can use it like:

<p>
  {{ floor | async | replaceWordLoby }}
</p>

stackblitz

  • Related