How to use Angular 2 built-in directives – *ngIf and *ngFor

Standard

In this post we will briefly explain what are the structural directives and why they make our life easier…

Structural Directives

Basically these kind of directives actually change the HTML layout – they either add or remove a DOM elements.

*ngIf

As you can guess from the title, this directive will allow us to show or hide some div for example, depending on a certain condition.

So imagine that you want to display some text after someone clicks a button or even after exactly 3 clicking, like in the following example:

2016-08-02_17-20-16

 

Firstly, we need to define our class, where we will have two properties: counter and requiredClicks and one function clicked()

The counter will increase every time the function is called.

The requiredClicks parameter will be used as a condition on whether to show some DOM element or not, but you will see more about it later on.

The function clicked() will do something when the button is clicked.

@Component({
  selector: 'my-app',
  template : `
     <div>
       <p>Please click the button {{ requiredClicks }} times </p>
       <button (click) = "clicked()">Test me</button>
     </div>`
})
export class App {
  counter: number = 0;
  requiredClicks: number = 3;
  clicked() {
    this.counter += 1;
  }
}

The next thing is to define a DOM element in our template which will “look” if some condition is satisfied. In our case we will define div element with a directive NgIf which will only come true if we clicked 3 times on the button.

If counter > requiredClicks – 1 is true, than every child element of the current div will be displayed.

@Component({
  selector: 'my-app',
  template : `
     <div>
       <p>Please click the button {{ requiredClicks }} times</p>
       <button (click) = "clicked()">Test me</button>
       <div *ngIf = "counter > requiredClicks - 1">
          <div>The button was clicked {{ counter }} times</div>
       </div>
     </div>`
})
export class App {
  counter: number  = 0;
  requiredClicks: number = 3;
  clicked() {
    this.counter += 1;
  }
}

Looks really intuitive, right?

Let’s continue with another useful directive:

*ngFor

When I wondered what should be the mock data for my next example I saw few kids playing Pokemon Go so let’s use the names of the most famous pokemons 😛

Capture

@Component({
  selector: 'my-app',
  template : `
<div>
<ul *ngFor="let pokemon of pokemons">
	<li>{{ pokemon }}</li>
</ul>
</div>
`
})
export class App {
  pokemons: string[] = ["Charizard", "Pikachu", "Charmander", "Bulbasaur"];
}

As a normal for loop with the syntax “let pokemon of pokemons” we are saying that we will use the name “pokemon” for every element from the given array called “pokemons”, just like we are normally using index or i. Than we will display every element from our array in “li” tag.

  • Charizard
  • Pikachu
  • Charmander
  • Bulbasaur

Hope this content would be useful for you.

Cheers!

Creating custom pipes in Angular 2

Standard

pipe.png

In this post we will discuss:

  • What is Angular 2 pipe
  • How to use it
  • How to make custom pipes

Pipes

In my last post we were discussing how to apply some styles to Angular 2 variable. Now we will take a look at how to format such variable in a different way.

You can think of pipes as some sort of filters or data formatters, which can apply styles to DOM elements, by binding to variables with Angular 2.

In Angular 2 we have pre-defined pipes, which allow us to make string uppercase or lowercase, to format data string and so much more.

Usage

As you can see in the code snippet, the only thing that we need to do, is to declare we want to use pipe with this symbol “|” and to specify which pipe from the core you want to use.

import { Component } from '@angular/core';
@Component({
	selector: 'my-pipe',
	template: '<span> {{ myString | uppercase }} </span>',
})
export class PipeComponent{
	myString: string = 'test';
}

The key part here is  {{ myString | uppercase }} where you are saying something like “I want to apply the “uppercase” filter to myString”.

In the Angular 2 core, you can find others pre-defined pipes, such as LowerCasePipe, PercentPipe, ReplacePipe, SlicePipe, DatePipe and more (link to the docs).

It is worth it to pay special attention to the pipe DatePipe. If we set our variable myDate, as follows:

myDate: number = Date.now();

The output of {{ myDate }} would be 1468917543306, which is not very readable.

However if we apply the date pipe:

{{ myDate| date}}

The output would be:  ‎Jul‎ ‎19‎, ‎2016.

We can also apply additional formatting:

{{ myDate | date : yMMMMd}}

will display the full month – July instead of only Jul (December instead of Dec)

Custom Pipes

In this section we will create our personal pipe, which will apply filter to array of numbers.

So let’s create a file called pipes.component.ts


import { Component } from '@angular/core';
import { FilterArray } from './custom.pipe';

@Component({
	moduleId: module.id,
	selector: 'my-pipe',
	templateUrl: 'pipes.component.html',
	styleUrls: ['pipes.component.css'],
	pipes: [FilterArray]
})
export class PipeComponent{
 	value: number[] = [1,2,3,4,5,6,7,8,9,10];
}

We will need to import our custom pipe and in the @Component decorator we need to state that we will use it.

The file custom.pipe.js would look like this:

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

@Pipe({name: 'filterArray'})
export class FilterArray implements PipeTransform {
  transform(array: number[], parameter: number): number[] {
   const newArray: number[] = [];
   if(isNaN(parameter)){
   	parameter = 10; // set up our default parameter to be 10 if we don't specify it.
   }
    for(let i = 0; i < array.length; i++){
if(array[i] > parameter){
    		newArray.push(array[i]);
    	}
    }
   return newArray;
  }
}

Here the new part is that we need to import the Pipe decorator and the PipeTransform interface from the core.

With @Pipe({name: ‘filterArray’}) we specify how our pipe will be named.

Our class FilterArray will implement a specific version of the transform function, so the following code:

{{ value | filterArray : 6}}

will display only the digits greater that 6.

So our initial array [1,2,3,4,5,6,7,8,9,10] will display as [7,8,9,10].

 

Feel free to comment or share and stay tuned for more Angular 2 posts.

 

 

Angular 2 CSS style bindings

Standard

In this post we will take a look on how to bind different styles to DOM elements in Angular 2.

You are all familiar with the following markup, right?

<div style="color:red;">Angular 2 is awesome</div>

Now, let’s put some Angular 2 sugar on it:

<div [ngStyle] = "{color: "red";}">Angular 2 is awesome</div>

Ok, it does absolutely the same thing as a simple html style. So why we should bother using it?

There is something called Angular 2 Directives, which helps us get some dynamic in our front-end. Now is the time to mention that there are 3 types of directives:

– Components
– Structural directives
– Attribute directives
In our example we used the attribute directives. Their purpose is to change the behavior of any DOM element. And that is exactly what we need.

Imagine if you don’t want your color always to be red, in some conditions you want it to be green. Here the directive comes in. We simply need to put a variable instead of particular color.

Angular 2 is awsome
So far, so good. But you may wonder from where this variable comes in.

If you are familiar with the basic structure of Angular 2 application, you should know that we should have a basic component, like the one below:

@Component({
  selector: 'test-styles',
  templateUrl: 'app/app.component.html'
})
export class AppComponent {
  //you can either define myColor in the class
  public myColor: string = ‘red’;
  //or you can create a function to define it
  getColor() {
    return 'green';
  }
}

And here is how app/app.component.html looks like:

<div style="color: red">Angular 2 is awesome</div>
<div [ngStyle] = "{color: "red"}">Angular 2 is awesome</div>
<div [ngStyle] = "{color: "myColor"}">Angular 2 is awesome</div>
<div [ngStyle] = "{color: "getColor()"}">Angular 2 is awesome</div>

In browser the final result would be:

Angular 2 is awesome
Angular 2 is awesome
Angular 2 is awesome
Angular 2 is awesome

Angular 2 is also allowing us to use directives directly with CCS styles, so the following statement is valid one:

<div [style.color] = "red">Angular 2 is awesome</div>

Have you seen how much time we just saved?

Angular 2 is indeed awesome!