RUVIDEO
Поделитесь видео 🙏

Angular 9 Tutorial - 19 - Custom Pipes in Angular | How to create custom pipes in angular

In this video we will discuss about how to create a Custom Pipe in Angular. Let us understand this with custom pipe example.

The requirement is to implement a power calculator

Step 1 : create a custom pipe called ExponentialPipe. Right click on the "pipes" folder and add a new TypeScript file. Name it "exponential.pipe.ts". Copy and paste the following code.

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

@Pipe({
name:'exponential'
})
export class ExponentialPipe implements PipeTransform {
transform(value: number, exponent? : number) : number{
console.log("val- "+ value + ", exp-" + exponent);
return Math.pow(value, isNaN(exponent) ? 1 : exponent);
}
}

Code Explanation :
1. Import Pipe decorator and PipeTransform interface from Angular core

2. decorate "ExponentialPipe" class with Pipe decorator to make it an Angular pipe

3. name property of the pipe decorator is set to exponential. This name can then be used on any HTML page where you want this pipe functionality.

4. ExponentialPipe class implements the PipeTransform interface. This interface has one method transform() which needs to be implemented.

5. Notice the transform method has 2 parameters. value parameter will receive the number to which we want calculate the power and exponent parameter receives the exponent value. The method returns a number after calculating the power using Math.

if you see errors for Math and isNaN then change your typescript version from use VS code version to Use Workspace version.

Step 2 : Register "ExponentialPipe" in the angular module where we need it. In our case we need it in the root module. So in app.module.ts file, import the ExponentialPipe and include it in the "declarations" array of NgModule decorator

import { ExponentialPipe } from './shared/pipes/exponential.pipe';

@NgModule({
declarations: [
AppComponent,
HomeComponent,
ExponentialPipe
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Step 3: Add two input tags in home.component.html as below

input type="number" #numref placeholder="Enter the number" [(ngModel)] = "num"


input type="number" #exponentref placeholder="Enter the exponent" [(ngModel)] = "exponent"

Add propertires for binding these input tags in home.component.ts file
num : number;
exponent : number;

Step 4 : In "home.component.html" use the "ExponentialPipe" as shown below. Notice we are passing exponent as an argument for the exponent parameter of our custom pipe. num gets passed automatically.

With Two way Binding:
num | exponential : exponent

With template reference variables or # variables

numref.value | exponential : exponentref.value


Search Tags
angular pipes | angular custom pipes | angular pipes example | angular pipe function | angular pipe async | custom pipes in angular 8 | custom pipes | custom pipes in angular | power calculator using custom pipes in angular

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Angular 9 Tutorial - 19 - Custom Pipes in Angular | How to create custom pipes in angular», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.