Salman Ahmad

1576728179

Angular tutorial : How to Create Custom Pipe in Angular

Pipes in Angular are a great way to transform and format data right from your templates. Out of the box you get pipes for dates, currency, percentage and character cases, but you can also easily define custom pipes of your own.This is where the concept of creating a Custom Pipe in Angular comes into play, allowing us to nicely extend our applications.

What are pipes in Angular?

Angular provides some helpful filters known as Pipes which makes it very easy to format or transform the data value according to our needs.
Pipes are used with a Pipe (|) character, it takes an input and returns a desired formatted output. Simple Right?

Angular has a few built-in Pipes that ship with the framework’s CommonModule, allowing us to make use of them in any module we’re writing.

Here are a few usual suspects we could encounter with Angular’s built-in Pipes:

  • DatePipe (for parsing Date objects)
  • UpperCasePipe (for uppercase-ing Strings)
  • LowerCasePipe (for lowercase-ing Strings)
  • CurrencyPipe (for formatting currencies)
  • AsyncPipe (for unwrapping asynchronous values, such as Observables!)

In simple terms, pipes allow us to write display value transformation right inside the template. Angular comes with stock or built in pipes to transform your values to what you want the user to see. For instance, the Date Pipe, allows you to change the date format and other aspects related to the date.

That’s the essence of a Pipe!

So, how do we use a Pipe? Let’s assume some simple component HTML with a binding of a Date stamp:

<div>
  <!-- Renders: 21/10/2019 -->
  <p></p>
</div>

This could render out as above with the formatted Date. So that’s a valid use case for Pipes! We don’t really want to fetch data and then loop through it all and convert each date from a Date object to a String, as we’d lose native Date object functionality and be duplicating values. It’s super convenient to use a Pipe and let it parse out for us!

Now you’re ready to start venturing into Custom Pipes! This will allow us to use a function to create our own input and output based on what you’re supplying. Let’s dive in!

Using Custom Pipes

Let’s assume an image was just uploaded via a drag and drop zone - and we’re getting some of the information from it. A simplified file object we’ll work with:


export class FileComponent {
  file = { name: 'logo.svg', size: 2120109, type: 'image/svg' };
}


Properties name and type aren’t what we’re really interested in to learn about Pipes - however size is the one we’d like. Let’s put a quick example together for how we’ll define the usage of our pipe (which will convert numbers into filesizes):


<div>
  <p></p>
  <p></p>
</div>

Creating a Custom Pipe

To create a Pipe definition, we need to first create a class (which would live in its own file). We’ll call this our FileSizePipe, as we are essentially transforming a numeric value into a string value that’s more human readable:

export class FileSizePipe {}


Now we’ve got this setup, we need to name our Pipe. In the above HTML, we did this:


<p></p>

So, we need to name the pipe “filesize”.

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

@Pipe({ name: 'filesize' })
export class FileSizePipe {}

All we need to do is supply a name property that corresponds to our template code name as well (as you’d imagine).

Don’t forget to register the Pipe in your @NgModule as well, under declarations:

// ...
import { FileSizePipe } from './filesize.pipe';

@NgModule({
  declarations: [
    //...
    FileSizePipe,
  ],
})
export class AppModule {}

NOTE : Pipes tend to act as more “utility” classes, so it’s likely you’ll want to register a Pipe inside a shared module. If you want to use your custom Pipe elsewhere, simply use exports: [YourPipe] on the @NgModule.

Pipe and PipeTransform

Once we’ve got our class setup, registered, and the @Pipe decorator added - the next step is implementing the PipeTransform interface:

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

@Pipe({ name: 'filesize' })
export class FileSizePipe implements PipeTransform {
  transform() {}
}

This creates a required contract that our FileSizePipe must adhere to the following structure:

export interface PipeTransform {
  transform(value: any, ...args: any[]): any;
}

Which is why we added the transform() {} method to our class above.

Pipe Transform Value

As we’re using our Pipe via interpolation, this is the magic on how we’re given arguments in a Pipe.

The file.size variable is passed straight through to our transform method, as the first argument.

We can call this our size and type it appropriately:

//...
export class FileSizePipe implements PipeTransform {
  transform(size: number) {}
}

From here, we can implement the logic to convert the numeric value into a more readable format of megabytes.

//...
export class FileSizePipe implements PipeTransform {
  transform(size: number): string {
    return (size / (1024 * 1024)).toFixed(2) + 'MB';
  }
}


We’re returning a type string as we’re appending 'MB' on the end. This will then give us:

<!-- 2.02MB -->

We can now demonstrate how to add your own custom arguments to custom Pipes.

Pipes with Arguments

So let’s assume that, for our use case, we want to allow us to specify the extension slightly differently than advertised.

Before we hit up the template, let’s just add the capability for an extension:

//...
export class FileSizePipe implements PipeTransform {
  transform(size: number, extension: string = 'MB'): string {
    return (size / (1024 * 1024)).toFixed(2) + extension;
  }
}

I’ve used a default parameter value instead of appending the 'MB' to the end of the string. This allows us to use the default ‘MB’, or override it when we use it. Which takes us to completing our next objective of passing an argument into our Pipe:

<!-- 2.02megabyte -->


And that’s all you need to supply an argument to your custom Pipe. Multiple arguments are simply separated by :, for example:

Don’t forget you can chain these pipes alongside others, like you would with dates and so forth.

Here’s the final assembled code:


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

@Pipe({ name: 'filesize' })
export class FileSizePipe implements PipeTransform {
  transform(size: number, extension: string = 'MB') {
    return (size / (1024 * 1024)).toFixed(2) + extension;
  }
}

Want a challenge? Extend this custom Pipe that allows you to represent the Pipe in Gigabyte, Megabyte, and any other formats you might find useful. It’s always a good exercise to learn from a starting point!

Learn More

#angular #developer

What is GEEK

Buddha Community

Angular tutorial : How to Create Custom Pipe in Angular
Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Roberta  Ward

Roberta Ward

1593184320

Basics of Angular: Part-1

What is Angular? What it does? How we implement it in a project? So, here are some basics of angular to let you learn more about angular.

Angular is a Typescript-based open-source front-end web application platform. The Angular Team at Google and a community of individuals and corporations lead it. Angular lets you extend HTML’s syntax to express your apps’ components clearly. The angular resolves challenges while developing a single page and cross-platform applications. So, here the meaning of the single-page applications in angular is that the index.html file serves the app. And, the index.html file links other files to it.

We build angular applications with basic concepts which are NgModules. It provides a compilation context for components. At the beginning of an angular project, the command-line interface provides a built-in component which is the root component. But, NgModule can add a number of additional components. These can be created through a template or loaded from a router. This is what a compilation context about.

What is a Component in Angular?

Components are key features in Angular. It controls a patch of the screen called a view. A couple of components that we create on our own helps to build a whole application. In the end, the root component or the app component holds our entire application. The component has its business logic that it does to support the view inside the class. The class interacts with the view through an API of properties and methods. All the components added by us in the application are not linked to the index.html. But, they link to the app.component.html through the selectors. A component can be a component and not only a typescript class by adding a decorator @Component. Then, for further access, a class can import it. The decorator contains some metadata like selector, template, and style. Here’s an example of how a component decorator looks like:

@Component({
    selector: 'app-root',
    templateUrl: 'app.component.html',
    styleUrls: ['app.component.scss']
})

Role of App Module

Modules are the package of functionalities of our app. It gives Angular the information about which features does my app has and what feature it uses. It is an empty Typescript class, but we transform it by adding a decorator @NgModule. So, we have four properties that we set up on the object pass to @NgModule. The four properties are declarations, imports, providers, and bootstrap. All the built-in new components add up to the declarations array in @NgModule.

@NgModule({
declarations: [
  AppComponent,
],
imports: [
  BrowserModule,
  HttpClientModule,
  AppRoutingModule,
  FormsModule
],
bootstrap: [AppComponent]
})

What is Data Binding?

Data Binding is the communication between the Typescript code of the component and the template. So, we have different kinds of data binding given below:

  • When there is a requirement to output data from our Typescript code in the HTML template. String interpolation handles this purpose like {{data}} in HTML file. Property Binding is also used for this purpose like [property] = “data”.
  • When we want to trigger any event like clicking a button. Event Binding works while we react to user events like (event) = “expression”.
  • When we can react to user events and output something at the same time. Two-way Binding is used like [(ngModel)] = “data”.

image for understanding data binding

#angular #javascript #tech blogs #user interface (ui) #angular #angular fundamentals #angular tutorial #basics of angular

akshay L

akshay L

1613737472

Angular Tutorial | Angular Tutorial For Beginners | Angular Training | Intellipaat

In this Angular tutorial you will learn what is angular, angular architecture, what is typescript, Data binding & interpolation, angular components, Variable Declaration & Function Declaration, Encapsulation & Polymorphism in Angular, Angular Routing and Navigation, various angular basic & advanced concepts, hands-on demo on how to import & export data in angular, Angular JS vs Angular vs React JS and angular CLI among others.

#angular tutorial #angular tutorial for beginners #angular training

Sasha  Roberts

Sasha Roberts

1626834660

Angular Rxjs: Use .map() And Async Pipe (Refactor Your Code)

In this video, we will see how to improve our code using the #rxs map operator and #angular #async pipe.

The components should be clean and minimal and should not have code that manipulates the data. Responsible for data manipulation is a service.
The goal is to prepare our data and return an #observable pipe so that we can use an #async pipe in the template.

code: https://github.com/profanis/codeShotsWithProfanis/tree/13/rxjsMapAndAsyncPipe

#angular #rxjs #observable #map #async

#angular rxjs #angular #angular tutorial #what is angular

Salman Ahmad

1588747755

Deploy Angular 10/9 App to Production with Firebase Hosting

In this tutorial, I am going to share with you How to Deploy Angular 10/9 App to Production with Firebase Hosting?.

#angular #firebase #popular tutorials #angualr firebase deploy #angular app #angular tutorial #firebase tutorial