top

Search

Angular JS Tutorial

Directives are one of the most attractive features in Angular. Directives allow developers to write code to attach some sort of behavior to the DOM elements. There are two kinds of directives in Angular -Structural DirectivesAttribute DirectivesAt the core, a directive is a function that executes whenever the Angular compiler finds it in the DOM. Angular directives are used to extend the power of the HTML by giving it new syntax.Structural DirectivesStructural directives allow us to add, remove or modify the DOM elements in the page or within components. There are two structural directives in Angular - NgIf and NgFor.NgIf is a structural directive that can be used to display DOM elements based on a certain condition. It is the simplest structural directive and the easiest to understand. It takes a boolean expression and makes an entire chunk of the DOM appear or disappear. The condition can be a boolean value, a statement that returns a boolean value or a method that returns a boolean value. When the expression evaluates to true, Angular renders the template provided in a then clause, and when false or null, Angular renders the template provided in an optional else clause. The default template for the else clause is blank. Let’s have a look at an example.In the above code snippet, you can see how we have used the NgIf directive. The *ngIf syntax is used to specify a boolean value. If the value is true (or if it evaluates to true), the DOM elements with the directive is rendered otherwise it is removed from the page (or is not rendered).The isAdmin property is of the type boolean and is initially set to true which makes the first div with the text color Red visible on the page, while the second div with the text color green is not rendered on the page.You'll see a directive spelled in both UpperCamelCase and lowerCamelCase. Already you've seen NgIf and ngIf. There's a reason. NgIf refers to the directive class while ngIf refers to the directive's attribute name. In code, you will always be using ngIf to actually use the directive.Instead of just having a boolean value, let’s have a look at another example where we will have a function passed to the NgIf directive.In the above code, we have replaced the boolean property with an actual method called isAdmin(). The method simply returns a boolean value but in a real application, it can have any complex logic. Here is the output.Another structural directive that you must know and will be used almost all the time in your code when writing Angular apps is NgFor. NgFor is a directive that is used when we need to render data from an iterable or simply put, an array. Let’s have a look at an example.Consider that we have an array of strings as shown below. It contains a few string values, fruit names in this case. To render this array on the page in the component, we need to use NgFor.On the right, you can see how we have used NgFor. Similar to using NgIf, here also we need to use the asterisk (*) symbol. This is required for some internal Angular compilation requirements.The rest of the syntax is very similar to a for-loop or a For-each loop if you are from a C# background.Items are the name of the array and item is a temporary variable that will contain one value from the array, for each iteration of the loop. For each iteration, a ‘li’ element will be rendered on the page. In our case, here is the output.Let’s have a look at another, a little more complicated real-world example. Instead of having simple strings stored in an array, here we are storing a little more data, JSON objects in the array.Each object contains two properties, name, and age of some people. To render this data on the page, we can use the following code in the HTML template.Here is the output. Simple, right?You can style the HTML however you want.You may want to use NgFor and NgIf on the same DOM element. This is a very common use-case but it is not allowed to have both the structural directives on the same DOM element. There is a solution to the problem though.Let’s look at another example. Consider that in the above example, we only want to display the names of the people who are 21 or older which will clearly remove Marcela from the list (since she is only 19). Now ideally, you would do something like this.If you try that, you will encounter the following error in the browser’s console windows and the page will go blank.The error message is clear enough. It tells you that you cannot have two attributes prefixed with * in the same DOM element which means that you cannot have *ngFor and *NgIf together. The solution to the problem lies in the element <ng-container> that Angular provides.<ng-container> element allows you to use separate elements for each structural directive, but it is not stamped to the DOM.Here is how you can use it.The <ng-container> element is not rendered by itself, therefore, using a NgFor with it will not cause issues. The li element will only be rendered if the age is greater than 19 else, an empty <ng-container> element will be written to the DOM which is nothing.Here is the output you will get.Perfect, isn’t it? Try playing around with different types of data and using NgIf and NgFor to solve trivial issues.Attribute DirectivesThe attribute directive changes the appearance or behavior of a DOM element. These directives look like regular HTML attributes in templates but they have their implementation-defined by Angular. The ngModel directive which is used for two-way is an example of an attribute directive.NgSwitchIt is used whenever you want to display an element tree consisting of many children. The Angular places only selected element tree into the DOM based on some condition.The NgSwitch directive is used in combination with NgSwitchCase and NgSwitchDefault directives. The NgSwitch directive on a container specifies an expression to match against. The expressions to match are provided by NgSwitchCase directives on views within the container.Every view that matches is rendered. If there are no matches, a view with the NgSwitchDefault directive is rendered. Elements within the NgSwitch statement but outside of any NgSwitchCase or ngSwitchDefault directive are preserved at the location. Let’s have a look at an example.Consider the following array.Now, if you want to display a template based on the value of a country for each person in the array, you can either use a number of NgIfs or a NgSwitch. Here is the HTML code that explains how to use NgSwitch.The NgFor loop will iterate over each item in the array and NgSwitch directive will try to match the value of the country with the values used in with NgSwitchCase directives. When the value matches, the corresponding template is rendered. Here is what the output will look like.In a nutshell, NgSwitch saves the trouble of using multiple NgIfs.NgStyleBased on the component state, dynamic styles can be set by using NgStyle. Many inline styles can be set simultaneously by binding to NgStyle. It is a very simple directive and works very similar to the style HTML attribute which is used to apply inline CSS styles.Consider the following code snippet where we have a property called myFavoriteColor defined and it has the value green.In the HTML template, using the NgStyle directive, we can use the property to define the color of the text.The first line of code uses a static string red as the color of the text and the second one used the myFavoriteColor property. Here is how the output looks like.NgClassIt controls the appearance of elements by adding and removing CSS classes dynamically. The ngClass directive will take an expression that will be used to determine which state styles to apply at a given time to the styled element.The expression passed on to NgClass can be an object, an array or a string.For our demonstration, let’s define a few CSS classes in the app.component.css file which is the CSS file for the AppComponent component.Next, we will use the NgClass directive to add these classes (or a combination of these classes to HTML elements.In the first line, we are simply passing in a string to the ngClass directive. Note that we are using property binding (the square bracket syntax). In the second and third line, we are passing in a JSON object where each key-value pair specifies whether a class will be applied or not.For now, we have passed in the values true and false, but this can easily be replaced with actual properties and even methods defined in the component class.Lastly, we can also pass in an array of strings where each element is a CSS class. All the classes passed to the array are applied. Here is how the output looks like.NgNonBindableWe use NgNonBindable when we want to tell Angular not to compile, or bind, a particular section of our page. The most common example of this is if we wanted to write out some Angular code on the page, for example, if we wanted to render out the text {{ name }} on our page, like so:Because we have used ngNonBindable directive, the text inside the <span> tag will not be compiled and will be rendered as it is. Here is how the output looks like.
logo

Angular JS Tutorial

Angular Directives

Directives are one of the most attractive features in Angular. Directives allow developers to write code to attach some sort of behavior to the DOM elements. There are two kinds of directives in Angular -

  • Structural Directives
  • Attribute Directives

At the core, a directive is a function that executes whenever the Angular compiler finds it in the DOM. Angular directives are used to extend the power of the HTML by giving it new syntax.

Structural Directives

Structural directives allow us to add, remove or modify the DOM elements in the page or within components. There are two structural directives in Angular - NgIf and NgFor.

NgIf is a structural directive that can be used to display DOM elements based on a certain condition. It is the simplest structural directive and the easiest to understand. It takes a boolean expression and makes an entire chunk of the DOM appear or disappear. The condition can be a boolean value, a statement that returns a boolean value or a method that returns a boolean value. When the expression evaluates to true, Angular renders the template provided in a then clause, and when false or null, Angular renders the template provided in an optional else clause. The default template for the else clause is blank. Let’s have a look at an example.

Angular Directives

Angular Directives

In the above code snippet, you can see how we have used the NgIf directive. The *ngIf syntax is used to specify a boolean value. If the value is true (or if it evaluates to true), the DOM elements with the directive is rendered otherwise it is removed from the page (or is not rendered).

The isAdmin property is of the type boolean and is initially set to true which makes the first div with the text color Red visible on the page, while the second div with the text color green is not rendered on the page.

Angular Directives

You'll see a directive spelled in both UpperCamelCase and lowerCamelCase. Already you've seen NgIf and ngIf. There's a reason. NgIf refers to the directive class while ngIf refers to the directive's attribute name. In code, you will always be using ngIf to actually use the directive.

Instead of just having a boolean value, let’s have a look at another example where we will have a function passed to the NgIf directive.

Angular Directives

In the above code, we have replaced the boolean property with an actual method called isAdmin(). The method simply returns a boolean value but in a real application, it can have any complex logic. Here is the output.

Angular Directives

Another structural directive that you must know and will be used almost all the time in your code when writing Angular apps is NgFor. NgFor is a directive that is used when we need to render data from an iterable or simply put, an array. Let’s have a look at an example.

Consider that we have an array of strings as shown below. It contains a few string values, fruit names in this case. To render this array on the page in the component, we need to use NgFor.

Angular Directives

On the right, you can see how we have used NgFor. Similar to using NgIf, here also we need to use the asterisk (*) symbol. This is required for some internal Angular compilation requirements.

The rest of the syntax is very similar to a for-loop or a For-each loop if you are from a C# background.

Items are the name of the array and item is a temporary variable that will contain one value from the array, for each iteration of the loop. For each iteration, a ‘li’ element will be rendered on the page. In our case, here is the output.

Angular Directives

Let’s have a look at another, a little more complicated real-world example. Instead of having simple strings stored in an array, here we are storing a little more data, JSON objects in the array.

Angular Directives

Each object contains two properties, name, and age of some people. To render this data on the page, we can use the following code in the HTML template.

Angular Directives

Here is the output. Simple, right?

Angular Directives

You can style the HTML however you want.

You may want to use NgFor and NgIf on the same DOM element. This is a very common use-case but it is not allowed to have both the structural directives on the same DOM element. There is a solution to the problem though.

Let’s look at another example. Consider that in the above example, we only want to display the names of the people who are 21 or older which will clearly remove Marcela from the list (since she is only 19). Now ideally, you would do something like this.

Angular Directives

If you try that, you will encounter the following error in the browser’s console windows and the page will go blank.

Angular Directives

The error message is clear enough. It tells you that you cannot have two attributes prefixed with * in the same DOM element which means that you cannot have *ngFor and *NgIf together. The solution to the problem lies in the element <ng-container> that Angular provides.

<ng-container> element allows you to use separate elements for each structural directive, but it is not stamped to the DOM.

Here is how you can use it.

Angular Directives

The <ng-container> element is not rendered by itself, therefore, using a NgFor with it will not cause issues. The li element will only be rendered if the age is greater than 19 else, an empty <ng-container> element will be written to the DOM which is nothing.

Here is the output you will get.

Angular Directives

Perfect, isn’t it? Try playing around with different types of data and using NgIf and NgFor to solve trivial issues.

Attribute Directives

The attribute directive changes the appearance or behavior of a DOM element. These directives look like regular HTML attributes in templates but they have their implementation-defined by Angular. The ngModel directive which is used for two-way is an example of an attribute directive.

NgSwitch

It is used whenever you want to display an element tree consisting of many children. The Angular places only selected element tree into the DOM based on some condition.

The NgSwitch directive is used in combination with NgSwitchCase and NgSwitchDefault directives. The NgSwitch directive on a container specifies an expression to match against. The expressions to match are provided by NgSwitchCase directives on views within the container.

Every view that matches is rendered. If there are no matches, a view with the NgSwitchDefault directive is rendered. Elements within the NgSwitch statement but outside of any NgSwitchCase or ngSwitchDefault directive are preserved at the location. Let’s have a look at an example.

Consider the following array.

Attribute Directives

Now, if you want to display a template based on the value of a country for each person in the array, you can either use a number of NgIfs or a NgSwitch. Here is the HTML code that explains how to use NgSwitch.

Attribute Directives

The NgFor loop will iterate over each item in the array and NgSwitch directive will try to match the value of the country with the values used in with NgSwitchCase directives. When the value matches, the corresponding template is rendered. Here is what the output will look like.

Attribute Directives

In a nutshell, NgSwitch saves the trouble of using multiple NgIfs.

NgStyle

Based on the component state, dynamic styles can be set by using NgStyle. Many inline styles can be set simultaneously by binding to NgStyle. It is a very simple directive and works very similar to the style HTML attribute which is used to apply inline CSS styles.

Consider the following code snippet where we have a property called myFavoriteColor defined and it has the value green.

NgStyle

In the HTML template, using the NgStyle directive, we can use the property to define the color of the text.

NgStyle

The first line of code uses a static string red as the color of the text and the second one used the myFavoriteColor property. Here is how the output looks like.

NgStyle

NgClass

It controls the appearance of elements by adding and removing CSS classes dynamically. The ngClass directive will take an expression that will be used to determine which state styles to apply at a given time to the styled element.

The expression passed on to NgClass can be an object, an array or a string.

For our demonstration, let’s define a few CSS classes in the app.component.css file which is the CSS file for the AppComponent component.

NgClass

Next, we will use the NgClass directive to add these classes (or a combination of these classes to HTML elements.

NgClass

In the first line, we are simply passing in a string to the ngClass directive. Note that we are using property binding (the square bracket syntax). In the second and third line, we are passing in a JSON object where each key-value pair specifies whether a class will be applied or not.

For now, we have passed in the values true and false, but this can easily be replaced with actual properties and even methods defined in the component class.

Lastly, we can also pass in an array of strings where each element is a CSS class. All the classes passed to the array are applied. Here is how the output looks like.

NgClass

NgNonBindable

We use NgNonBindable when we want to tell Angular not to compile, or bind, a particular section of our page. The most common example of this is if we wanted to write out some Angular code on the page, for example, if we wanted to render out the text {{ name }} on our page, like so:

NgNonBindable

Because we have used ngNonBindable directive, the text inside the <span> tag will not be compiled and will be rendered as it is. Here is how the output looks like.

NgNonBindable

Leave a Reply

Your email address will not be published. Required fields are marked *

Suggested Tutorials

Node JS Tutorial

Build various types of web applications,command-line application,etc.
Node JS Tutorial

Build various types of web applications,command-line application,etc....

Read More

JavaScript Tutorial

JavaScript is a dynamic computer programming language for the web. JavaScript was first known as LiveScript. Later on, Netscape changed its name to JavaScript because of its popularity and the excitement generated by it. JavaScript is lightweight and most commonly used as a part of web pages supported by most web browsers like Chrome, Internet Explorer, Opera, Safari, Edge, and Firefox.
JavaScript Tutorial

JavaScript is a dynamic computer programming language for the web. Jav...

Read More