Showing posts with label Angular 6. Show all posts
Showing posts with label Angular 6. Show all posts

Thursday, November 29, 2018

Angular chaining pipes

Chaining pipes is Angular nothing but arranging more than one pipe in sequence so that the input value gets transformed in stages through the various pipes chained together. The successive pipes in the chain should be separated by a pipe symbol.

{{<input value> | <pipe 1> | <pipe 2> | . . . | <pipe n>}}

While chaining pipes we can also specify parameters for any of the pipes in the chain, in which case the pipe and its parameter are separated by a colon (:) symbol. Parameters are optional, also we can selectively specify parameters for certain pipes in the chain and ignore for other pipes.

 {{<input value> | <pipe 1> : <parameter> | <pipe 2> | . . . | <pipe n> <parameter>}}

In the following example we will use a date pipe, followed by an uppercase pipe. The input value will be a date object which holds the current date.

Wednesday, November 28, 2018

Angular built-in pipes

Angular pipes provide us an important feature of formatting / transforming data to a desired way in the view.

For example date formatting is one common requirement which we need in all applications. Angular provide different Date Pipes like shortDate, longDate, fullTime etc which come in handy to display different formats of dates in the UI.

Angular Pipes

Pipes in Angular are used to format / transform data and display it in the UI. Pipes are not new in Angular, for those familiar with AngularJS can connect the same concept in Angular. The very basic pipe takes one input followed by the pipe | symbol which is again followed by the type of pipe to be used for transformation.

<input> | <pipe type>

Pipes can have additional parameters to add more formatting / specification on how the transformation should be done, parameters are followed by the pipe type with a colon : symbol

<input> | <pipe type> : <parameter>

Pipes can have multiple parameters chained in sequence, each parameter in the chain is separated with a colon : symbol

<input> | <pipe type> : <parameter1> : <parameter2> . . . : <parameterN>

Tuesday, November 27, 2018

Custom Structural Directive example

Structural directive in Angular manipulate the DOM by adding/removing a set of elements. Attribute directives on the other hand decorate the element with more content/features. Structural directives can be identified with the * mark in front of them. In this example we will create a simple structural directive *ngShow which will show/hide the embedded content based on a condition. Let us start by creating a new directive using the following ng command.

Custom Structural Directive

Structural directive in Angular alter the DOM by adding/removing elements to the DOM based on specific conditions.  Attribute directives on the other hand can be used to app specific properties / styles to the element which is using the directive. We saw the example of the highliter Attribute directive which added a background color for highlighting the element which uses the directive.

ngIf is a built-in structural directive, based on the condition/expression we pass to this directive we can show/hide a block of elements in the DOM. Structural directives are represented with a * symbol before the directing like *ngIf.

Monday, November 26, 2018

Passing values to Custom Attribute Directive

In the Highlighter directive custom attribute directive example we saw how to create a custom attribute directive and use it in a component. In the Highlighter directive example we just had to add the directive name in the HTML element and that’s it the directive used ElementRef to get a handle of the DOM element and set the background color of the element.

There are cases where we want to pass some values from the HTML element to the directive to perform more meaningful operations in the directive. To pass values to the Directive class we have to declare the parameters as @Input in the directive class as follows.

export class ExpValidatorDirective implements OnChanges  {
  @Input() expression: string
  ...
}

And when using the directive in the Component, we can pass values to the directive like properties as follows.

<span expValidator [expression]="value to be passed to the Directive"> </span>

In the following example we will create an Expression validator directive, this directive will take 2 parameters the first one is a regular expression and the second one is the value to evaluate. 

Sunday, November 25, 2018

Angular – ViewChild Decorator

The ViewChild decorator in Angular is used to query DOM elements in a Template or Directive or a Child component.

Accessing DOM elements can be done by adding a #reference to the element in the template and by using the ViewChild decorator in the component to get a handle to the element. The reference to the element will be available in the component only after the view initialization is completed, hence we can use this handle in the ngAfterViewInit lifecycle hook.

The following sample adds a reference #refInput to the template, and uses the reference to access the DOM element in the component.

Angular – ElementRef

Angular provides different ways to access the DOM elements directly in the component / directive instance. If you are familiar with react you can think of something similar to refs in react which provides direct access to DOM elements.

ElementRef is one of the options provided in Angular to access DOM elements. ElementRef is bound to a single element and allows us to reference that element in the component class and alter the element. Angular also provides reference options like TemplateRef, ViewRef, ComponentRef and ViewContainerRef to reference DOM elements.

ElementRef comes in handy when we create custom directives, using ElementRef we can get a handle to the DOM element which uses the directive. Using the handle we can get/set properties from the DOM element.

Using ElementRef to access a DOM element directly is not a recommended approach and should be avoided if possible. Within a single component using ElementRef can be replaced with using model binding etc.

Custom Attribute Directive example

Custom Attribute directives can be attached to HTML elements like input, span etc to provide more features / functionalities to the element. Custom directives can be created using the ng generate directive command. Similar to components which use the @Component decorator, a directive uses the @Directive decorator. The directive class can implement the life-cycle hooks and alter the bahaviour of the directives.

In the following example let us create a very simple Highlighter directive which can be used in a label/span tag and will highlight the label with a color. Let us begin by creating a new directive using the ng generate command as follows.

Wednesday, November 21, 2018

Angular Custom Directives

Directives in angular are special notations which allows us to extend the behavior of DOM elements in the view template. Like components directives also have a selector and used in the view template to extend the functionality of HTML tags. When the Angular compiler finds a directive in the view template it executes the class behind the directive and modifies the DOM accordingly.

Angular provides built-in directives like ngIf, ngFor etc, apart from these we can also define our own custom directives and use them in the view template.

Custom directives can be created using the ng generate directive command as follows.

Monday, November 19, 2018

Types of Angular Directives

Angular has 3 different types of directives
       1.       Component Directive 
       2.       Structural Directive &
       3.       Attribute Directive

What is an Angular Directive


Directives in angular are special notations which allows us to extend the behavior of DOM elements in the view template. For example the ngFor is a built-in Angular directives, the ngFor directive is used to repeat a set of HTML elements for a predefined number of times thereby creating a table/list structure in the view template.

Directives are not totally new to the Angular world, we had directives like ng-repeat in AngularJS which did the same thing as ngFor. Since Angular has evolved from AngularJS, the Directives structure and templates have also evolved with it since Angular 2+

Directives are classes declared using @Directive. Directives also have different life-cycle hooks which we can implement to alter the behavior of the Directives.

A new directive can be created using the following CLI command.

ng generate directive

Sunday, November 18, 2018

Angular Lifecycle Hooks

ngOnDestroy lifecycle hook


The ngOnDestroy lifecycle hook gets executed just before Angular destroys the directive/component. Use this event to unsubscribe Observables and detach event handlers to avoid memory leaks.  It is the perfect place to clean the component. Let us see on how to use this lifecycle hook with a simple example.

Similar to our ngOnOnit example, we have a service call using an observable to make a http ajax call to get data from a service, in this example we will use the ngOnDestroy hook to unsubscribe the observable and do a cleanup when the component in unloaded.

ngDoCheck lifecycle hook

The ngDoCheck lifecycle hook gets executed when Angular runs the change detection process. ngOnChanges also gets executed when changes are detected the difference is that ngOnChanges() detects changes for those properties which are passed by value. ngDoCheck() detects changes for those properties also which are passed by reference such as arrays. For performance reasons OnChanges does not fire when the input property is an array/object, in these cases we can use ngDoCheck to perform our own custom change detection.

Let us see how this works with a simple example. We will extend the example which we used for ngOnChanges, we will add one more @Input property to the child component, this time we will add an object instead of a string so that we can see that ngDoCheck gets triggered but not ngOnChanges when the object is changed.

ngOnInit lifecycle hook

The ngOnInt lifecycle hook is executed when the component is initialized, this event can be used to initialize data required by the component. The most common use of this event is to make ajax/api calls to fetch data required to be populated in the component. We can also use this event to initialize properties of the component. This hook gets executed after ngOnChanges() and before any child components are initialized.

Let us see how this works with a simple example. In this example we use the ngOnInit() event to call a service method which uses an Observable to get API data from a service. The response data is stored in a userList object, which can be rendered in the component UI.

ngOnChanges lifecycle hook

The ngOnChanges lifecycle hook is executed when any of the components data-bound input properties are changed. Let us see how this works with a simple example.

We have a parent component which has a nested child component. The parent component has a property “message”, the component also has a button on click of which we change the text of the message property in the button’s click handler. We embed a child component and pass the message as an @Input property to the child component. When we click the button in the parent component the message property changes and hence the value passed in the @Input property will also change, this should trigger the ngOnChanges lifecycle hook in the child component.

Saturday, November 17, 2018

Lifecycle hooks of an Angular Component


The following are the lifecycle hooks of an Angular component/directive. These life cycle hooks are executed in the order listed below.

What are Lifecycle Hooks?


An Angular component goes through different stages when it is initialized, changes and destroyed these stages are called lifecycle hooks. These lifecycle hooks helps us interact with the components and its properties through the various stages before it is rendered in the browser, we can make use of these lifecycle hooks to alter the behavior of the component. The constructor is the first method to be executed before any of the lifecycle hook is executed.

At a high level Angular application processing consists of the following 3 stages.