Understanding ViewEncapsulation in Angular

To understand ViewEncapsulation in Angular, first we should understand about Shadow DOM.  You can learn in detail about Shadow DOM here. Putting it in simple words, Shadow DOM brings Encapsulation in HTML Elements. Using the Shadow DOM , markup, styles, and behaviors are scoped to the element and do not clash with other nodes of the DOM. Shadow DOM is part of Web Components, which encapsulates styles and login of element.

Angular Components are made up of three things:

  1. Component class
  2. Template
  3. Style

Combination of these three makes an Angular component reusable across application. Theoretically, when you create a component, in some way you create a web component (Theoretically, Angular Components are not web components) to take advantage of Shadow DOM. You can also use Angular with browsers, which does not support Shadow DOM because Angular has its own emulation and it can emulate Shadow DOM.

To emulate Shadow DOM and encapsulate styles, Angular provides there types of ViewEncapsulation. They are as follows:


Let us try to understand it using an example. I have created a component, as shown below:




We are setting the style of h1 in the component CSS. We have also created another component:

In AppChildComponent, we are also using h1 tag. To understand different ViewEncapsulation options, we will change the metadata of AppComponent.

Let us start with ViewEncapsulation.None, in this option,

  1. There is no shadow DOM
  2. Style is not scoped to component


As you run the application, you will find h1 style has applied to both components, even though we set style only in AppComponent. It happened because in AppComponent we have set encapsulation property to ViewEncapsulation.None.

In the browser when you examine source code, you will find h1 style has been declared in the head section of the DOM.

Therefore, in ViewEncapsulation.None, style gets move to the DOM head section and is not scoped to the component.  There is no Shadow DOM for the component and component style can affect all nodes of the DOM.

Next, let us explore ViewEncapsulation.Native, in this option:

  1. Angular will create Shadow DOM for the component.
  2. Style is scoped to component


As you run the application, you will find h1 style has applied to both components, even though we set style only in AppComponent. It happened because in AppComponent we have set encapsulation property to ViewEncapsulation.Native, and we are using AppChildComponnet as child inside template of AppComponent.

Read full article on the Infragistics blog

Understating Angular Change Detection with example

Change Detection means updating the DOM whenever data is changed. Angular provides two strategies for Change Detection.

  1. Default strategy
  2. onPush strategy

In default strategy, whenever any data is mutated or changed, Angular will run change detector to update the DOM. In onPush strategy, Angular will only run change detector only when new reference is passed to @Input() data.

To update the DOM with updated data, Angular provides its own change detector to each component, which is responsible to detect change and update the DOM.

Let us say we have a MessageComponent as listed below:

In addition, we are using MessageComponent inside AppComponent as below,

Let us talk through the code: all we are doing is using MessageComponent as child inside AppComponent and setting value of person using the property binding. At this point on running the application, you will get name printed as output.

Next, let us go ahead and update firstname property on the button click in AppComponent class below:

As soon as we changed the property of mutable object P, Angular fires the change detector to make sure that the DOM (or view) is in sync with the model (in this case object p). For each property changes, Angular change detector will traverse the component tree and update the DOM.

Let us start with understanding about component tree. An Angular application can be seen as a component tree. It starts with a root component and then go through to child components. In Angular, data flows from top to bottom in the component tree.

Whenever @Input type property will be changed, Angular change detector will start form the root component and traverse all child components to update the DOM. Any changes in primitive type’s property will cause Angular change detection to detect the change and update the DOM.

In above code snippet, you will find that on click of the button, the first name in the model will be changed. Then, change detection will be fired to traverse from root to bottom to update the view in MessageComponent.

There could be various reasons of Angular change detector to come into action and start traversing the component tree. They are:

  1. Events fired such as button click, etc.
  2. AJAX call or XHR requests
  3. Use of JavaScript timer functions such as setTimeOut , SetInterval

Now, as you see,  a single property change can cause change detector to traverse through the whole component tree. Traversing and change detection is a heavy process, which may cause performance degradation of application. Imagine that there are thousands of components in the tree and mutation of any data property can cause change detector to traverse all thousand components to update the DOM. To avoid this, there could be scenario when you may want to instruct Angular that when change detector should run for a component and its subtree, you can instruct a component’s change detector to run only when object references changes instead of mutation of any property by choosing onPush ChangeDetection strategy.

You may wish to instruct Angular to run change detection on components and their sub-tree only when new references are passed to them versus when data is simply mutated by setting change detection strategy to onPush.

Let us go back to our example where we are passing object to MessageComponent. In the last example, we just changed firstname property and that causes change detector to run and to update the view of MessageComponent. However, now we want change detector to only run when reference of passed object is changed instead of just a property value. To do that let us modify MessageComponent to use OnPush ChangeDetection strategy. To do this set changeDetectionproperty of @Component decorator to ChangeDetectionStrategy.OnPush as shown in listing below:

At this point when you run the application, on click event of the button in AppComponent change detector will not run for MessageComponent, as only a property is being changed and reference is not changing. Since change detection strategy is set to onPush, now change detector will only run when reference of @Input property is changed.

In the above code snippet, we are changing reference of object instead of just mutating just one property. Now when you run application, you will find on the click of the button that the DOM is being updated with new value.

By using onPush Change Detection, Angular will only check the tree if the reference passed to the component is changed instead of some property changed in the object. We can summarize that, and Use Immutable Object with onPush Change Detection to improve performance and run the change detector for component tree when object reference is changed.

We can further improve performance by using RxJS Observables because they emit new values without changing the reference of the object. We can subscribe to the observable for new value and then manually run ChangeDetector.

Read full article on the Infragistics blog

How to deploy an Angular application to GitHub

In this article, we will follow a step-by-step approach to deploy an Angular application to a GitHub. We will create a project using Angular CLI  and then deploy that to GitHub. Let us get started.

Step 1

To create a project using Angular CLI. Run the command:

ng new demo

You need to make sure that Angular CLI is installed globally on your machine.

Step 2

Change directory to demo and open project in VS Code or any other IDE of your choice.  Modify AppComponent to add, subtract, multiply, and divide two numbers as shown in the below listing:

As you can see, that AppComponent is very simple and it contains code to perform basic calculator operations.

Next, modify the AppComponent template


Like the component class template, it is also very simple. It uses:

  • ngModel for two way data binding between input controls and properties
  • event binding to call a function on click of the button
  • interpolation to display the result

Step 3

Before we publish this application to GitHub, let us run it locally. To run it locally, run the command

ng serve

Your application should run on default port 4200 of localhost as shown in the image below:


Continue reading full articles on the Infragistics blog

How to do Conditional Validation on valueChanges method in Angular Reactive Forms

Read full article on the Infragistics blog

In this blog post, we will learn to use Angular Reactive Forms value change detection and enable conditional validation on basis of that.

Learn How to Create Your First Angular Reactive Form here

Let us say you have a Reactive Form created using FormBuilder class as shown below:

You have created loginForm, which has three controls: email, password, and phonenumber. Here, you are using FormBuilder to create a reactive form. On the component template, you can attach loginForm as shown in the code listing below. Using property binding, the formGroup property of the HTML form element is set to loginForm and the formControlName value of these controls are set to the individual FormControl property of FormBuilder.

We have also put error messages for email and phone number fields. Besides, that submit button would only be enabled when the form is valid.  Form submit is handled as shown in the listing below:

If the form is valid in browser console, you will get the output as below:

In addition, if there is an error, submit button would be disabled and an error message will be shown as below:

You can learn to create Custom Validators for Angular Reactive Forms here

Now assume a scenario that you have a radio button to send a notification. The user should able to select the send notification option, and on basis of that, certain FormControl will have some validation.

Consider the form below,

We have added a Send Notification option. If the user selects Phone to send notification then Phone Number field should be required, otherwise, it should not be. To achieve this we need to perform following tasks,

  1. Listening to changes
  2. Put conditional validation

To start with, let us modify our form to handle the notification. So now form has a notification FormControl with the default value set to null as shown in the listing below :

On the Reactive form template, we will add radio button group to handle Send Notification option.

Continue Reading full article on the Infragistics blog here

Simplifying ViewChild and ContentChild in Angular

Read full article on the Infragistics blog

In this blog post, we will learn about ViewChild and ContentChild in Angular.

Essentially ViewChild and ContentChild are used for component communication in Angular. Therefore, if a parent component wants access of child component then it uses ViewChild or ContentChild.

Any component, directive, or element which is part of a template is ViewChild and any component or element which is projected in the template is ContentChild.

ViewChild and ViewChildren

If you want to access following inside the Parent Component, use @ViewChild decorator of Angular.

  1. Child Component
  2. Directive
  3. DOM Element

ViewChild returns the first element that matches the selector.

Let us assume that we have a component MessageComponent as shown in the below listing:

We are using MessageComponent inside AppComponent as shown in below listing:

In application, you will get the output as below:

Here, MessageComponent has become child of AppComponent. Therefore, we can access it as a ViewChild. Definition of ViewChild is:

The Child Element which is located inside the component template”,

Here MessageComponent is located inside template of AppComponent, so it can be accessed as ViewChild.

We need to do following tasks:

  • Import ViewChild and AfterViewInit from @angular/core
  • Implement AfterViewInit life cycle hook to component class
  • Create a variable with decorator @ViewChild
  • Access that inside ngAfterViewInit life cycle hook

In the output console you will find reference of MessageComponent, also if you can notice that __proto__ of MessageComponnet is set to Object.

Continue reading on the Infragistics blog

How to dynamically create a Component in Angular

You can read full article on the Infragistics blog

In this article, we will learn to create a component dynamically. You may need to load a component dynamically in various scenarios such as want to show a popup modal etc.

Let us assume that, we have a component as listed below, which we will load dynamically.

To load MessageComponent dynamically you need a container. Let us say that we want to load MessageComponent inside AppComponent. We need a container element in the AppComponent.

Template of AppComponent is as below:

As you see that, we have an entry point template or a container template in which we will load MessageComponent dynamically.

In the AppComponent, we need to import following:

  1. ViewChild, ViewContainerRef, and ComponentFactoryResolver from @angular/core
  2. ComponentRef and ComponentFactory from @angular/core
  3. MessageComponent from message.component

After importing required things, AppComponnet will look like following listing:

We can access template as the ViewChild inside the Component class. Template is a container in which, we want to load the component dynamically. Therefore, we have to access temple as ViewConatinerRef.

ViewContainerRef represents container where one or more view can be attached. This can contain two types of views.

  1. Host Views
  2. Embedded Views

Host Views are created by instantiating a component using createComponent and Embedded Views are created by instantiating an Embedded Template using createEmbeddedView. We will use Host Views to dynamically load MessageComponent.

Let us create a variable called entry which will refer template element. In addition, we have injected ComponentFactoryResolver services to component class, which will be needed to dynamically load the component.

Keep in mind that entry variable which is reference of template element has API to create components, destroy components etc.

Now to create component, let us create a function. Inside the function, we need to perform following tasks,

  • Clear the container
  • Create a factory for MessageComponent
  • Create component using the factory
  • Pass value for @Input properties using component reference instance method

Putting everything, together createComponent function will look like listing below:

We can call createComponent function on click event of the button.

You can keep reading full article on the Infragistics blog

Step by Step creating Custom Pipe in Angular

Read full article on the Infragistics blog

Angular pipes take data as input and transform it to your desired output. For example, using interpolation you are displaying name of the product. Now you want the product name always displayed in the uppercase. You can do this using Angular pipe uppercase.

In above component, productName will be displayed in uppercase. Therefore, pipe takes an input and transforms it into desired output as shown below:

Angular library provides us many built-in pipes like

  • UpperCasePipe
  • LowerCasePipe
  • CurrencyPipe
  • PercentPipe
  • DatePipe etc.

Let us see how we could use the built-in currency pipe.

You can also pass parameters to a pipe using the colon. You can pass input to currency pipe as shown below:

Even though Angular provides many default pipes, there could be requirements when you create custom pipes. Creating a custom pipe is very as simple as creating a function.  Let us say that we want to create a pipe, which will capitalize first letter of each words in a string.

Consider below component,

This component will print names as below:

Now we want to capitalize the first letter of each word in the name. To do that we need to write a custom pipe.  To create a pipe, you need to follow these steps:

Read full article on the Infragistics blog

How to create Custom Validator for Angular Reactive Forms

Learn full article on the Infragistics blog

In this blog post, we will learn to create custom validators in Angular Reactive Forms. If you are new to reactive forms, learn how to create your first Angular reactive form here.

Let’s say we have a login form as shown in the listing below. Currently, the form controls do not have any validations attached to it.

Here, we are using FormGroup to create a reactive form. On the component template, you can attach loginForm as shown in the code listing below. Using property binding, the formGroup property of the HTML form element is set to loginForm and the formControlName value of these controls are set to the individual FormControl property of FormGroup.

This will give you a reactive form in your application:


Using Validators

Angular provides us many useful validators, including required, minLength, maxLength, and pattern. These validators are part of the Validators class, which comes with the @angular/forms package.

Let’s assume you want to add a required validation to the email control and a maxLength validation to the password control. Here’s how you do that:

To work with Validators, make sure to import them in the component class:

On the template, you can use validators to show or hide an error message. Essentially, you are reading the formControl using the get() method and checking whether it has an error or not using the hasError() method. You are also checking whether the formControl is touched or not using the touched property.

If the user does not enter an email, then the reactive form will show an error as follows:


Custom Validator

Let us say you want the age range to be from 18 to 45. Angular does not provide us range validation; therefore, we will have to write a custom validator for this.

In Angular, creating a custom validator is as simple as creating another function. The only thing you need to keep in mind is that it takes one input parameter of type AbstractControl and it returns an object of key value pair if the validation fails.

Let’s create a custom validator called ageRangeValidator, where the user should able to enter an age only if it’s in a given range.


The type of the first parameter is AbstractControl because it is a base class of FormControl, FormArray, and FormGroup, and it allows you to read the value of the control passed to the custom validator function. The custom validator returns either of the following:

1. If the validation fails, it returns an object, which contains a key value pair. Key is the name of the error and the value is always Boolean true.

2. If the validation does not fail, it returns null.

Learn full article on the Infragistics blog

Understanding @Output and EventEmitter in Angular



Read full article on the Infragistics blog

Angular is based on a one-directional data flow and does not have two-way data binding. So, how do you get a component to emit an event to another component?

In Angular, a component can emit an event using @Output and EventEmitter. Both are parts of the @angular/core.

Confused by the jargon? Let’s simplify it together. Consider the AppChildComponent as listed below:

There is a button in the AppChildComponent template which is calling the function handleclick. Let’s use the app-child component inside the AppComponent as shown in the listing below:

Here we’re using AppChildCopmponent inside AppComponent, thereby creating a parent/child kind of relationship, in which AppComponent is the parent and AppChildComponent is the child. When we run the application with a button click, you’ll see this message in the browser console:


So far, it’s very simple to use event binding to get the button to call the function in the component. Now, let’s tweak the requirement a bit. What if you want to execute a function of AppComponent on the click event of a button inside AppChildComponent?

To do this, you will have to emit the button click event from AppChildComponent. Import EventEmitter and Output from @angular/core.

Here we are going to emit an event and pass a parameter to the event. Consider the code below:

Right now, we are performing the following tasks in the AppChildComponent class:

1. Created a variable called counter, which will be passed as the parameter of the emitted event.

2. Created an EventEmitter valueChange, which will be emitted to the parent component on the click event of the button.

3. Created a function named valueChanged(). This function is called on the click event of the button, and inside the function event valueChange is emitted.

4. While emitting valueChange event, value of counter is passed as parameter.

Read full article on the Infragistics blog

What are @HostBinding() and @HostListener() in Angular?

Read full article on the Infragistics blog

To understand @HostListener and @HostBinding, you should have basic knowledge about directives in Angular. There are three types of directives in Angular:

  1. Component
  2. Attribute Directive
  3. Structural Directive

The basic difference between a component and a directive is that a component has a template, whereas an attribute or structural directive does not have a template. To understand these two concepts, let us start by creating a simple custom attribute directive. The directive below changes the background color of the host element:

To create a custom attribute directive, you need to create a class and decorate it with @Directive. In the constructor of the directive class, inject the objects ElementRef and Renderer. Instances of these two classes are needed to get the reference of the host element and of the renderer.

You can use the above attribute directive on a component template as shown in the listing below:

Here, the component class holding the host element is created as below:

Right now, the appChbgcolor directive will change the color of the host element.

@HostListener() decorator

In Angular, the @HostListener() function decorator allows you to handle events of the host element in the directive class.

Let’s take the following requirement: when you hover mouse on the host element, only the color of the host element should change. In addition, when the mouse is gone, the color of the host element should change to its default color. To do this, you need to handle events raised on the host element in the directive class. In Angular, you do this using @HostListener() .

To understand @HostListener() in a better way, consider another simple scenario: on the click of the host element, you want to show an alert window. To do this in the directive class, add @HostListener() and pass the event ‘click’ to it. Also, associate a function to raise an alert as shown in the listing below:

Read full article on the Infragistics blog