top
Easter Sale

Search

Angular JS Tutorial

Angular is an opinionated front-end javascript framework which means that it enforces a certain style of application development and project structure that developers need to follow to develop apps with Angular. However, it also offers enough flexibility to allow you to structure your project in an understandable and manageable manner.In this module, we will have a look at some of the most basic concepts that you need to understand before diving into the framework with more advanced concepts.ComponentsAngular apps are composed of components. A component is a reusable piece of functionality that can be used throughout the project or even be dropped into other Angular projects. A component has a user-interface defined by the component’s template and the business logic for the component is implemented by the component class. Since Angular is written using TypeScript, all the component class code is written in TypeScript.Components are the core building blocks of Angular applications. These components are composable which means that bigger components can be formed by using smaller components or that larger components can be broken down into multiple smaller components.TypeScript is an open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, and adds optional static typing to the language. TypeScript is designed for development of large applications and trans-compiles to JavaScript. Since modern browsers do not understand TypeScript, we need this transpilation process.Coming back to the project, we created in the last module, if you look inside the src/app folder, you can see a bunch of files there. Let’s have a look at each of these files and understand their role in the Angular project.In the above screenshot, you can see that there are a total of 6 files as of now inside the src/app folder.app.module.ts: This is the main module file for the project. Each Angular project is divided into modules to make the project management easy. By default, the whole project is a part of a single module but you can always create more modules. A module is a logical chunk of project resources that works independently or in combination with other modules. This file contains a module called AppModule.app.component.html: This file is the template file for the one and only component in our project as of now. This component is called the AppComponent. The extension html indicated that this file is an HTML document and will define the view of the component.app.component.css: This file work in combination with the HTML template and adds CSS styles to the HTML elements defined in that template. This only only contains CSS classes and styles.app.component.ts: This is the main class file for the AppComponent component. This file contains the TypeScript class for the component and all the business logic for this component goes inside this file.app.component.spec.ts: This file is for unit testing the AppComponent component. Let’s not worry about this for now. Feel free to delete the file if it bothers you too much.app-routing.module.ts: This is another module file for the project (just like the app.module.ts that contains the module AppModule) that handles routing or navigation for the whole project. It defines how different components will be presented to the user as the user navigates within the application.So, it is fairly evident from the above description of the files that a component is composed of 3 files -The HTML TemplateThe TS ClassThe CSS StylesNote: Having different files for template, TS class and CSS styles is the convention how components are set up in most applications. However, for simple and small components, you can define the template and CSS styles in the TS class file as well.Component LifecycleComponents are core building blocks of Angular applications. Each component is instantiated when it is required, it does its job and then gets destroyed to free us the memory. Component instances have a lifecycle as Angular creates, updates, and destroys them. Developers can tap into key moments in that lifecycle by implementing one or more of the lifecycle hook interfaces in the Angular core library.Lifecycle hooks allow us to execute our code when the components reach a specific stage in their lifecycle.For example, we may want to make a call to an external API as soon as a components finished loading or we may want to notify a web-service when a component is destroyed. We can do this with the help of lifecycle hooks.Here is some of the important lifecycle hooks that Angular provides for the components in the same sequence in which they are called after the constructor of the component class is executed.ngOnChanges(): called when Angular (re)sets the data bound properties.ngOnInit(): called after Angular first displays the data-bound properties and sets the directive/component's input properties.  It is generally use to perform complex initializations shortly after construction and to set up the component after Angular sets the input properties.You should avoid having these complete initialization logics in your constructors.Misko Hevery, the Angular team lead, explains why you should avoid complex constructor logic here.ngAfterContentInit(): called after Angular projects external content into the component's view / the view that a directive is in.ngAfterContentChecked(): called after Angular checks the content projected into the directive/component.ngAfterViewInit(): called after after Angular initializes the component's views and child views.ngOnDestroy(): called just before Angular destroys the component. This is the time to notify another part of the application that the component is going away.Classes, Constructors, Variables and TypesOpen the file src/app/app/component.ts and there is the code for the TypeScript class responsible for the AppComponent.In the above you can see that we have a class called AppComponent that has a member variable defined inside it. This class does not have a constructor defined, but we can always create a constructor manually as shown below.The code inside the constructor is executed as soon as the class is initialized.At line#9, a variable is declared named title and is initialized with the value ‘Test’ which is of the type string. Optionally, we can also specify the type explicitly.title: string = 'Test';Now, you can only assign values of type string to the title variable. If you try to store a number or a boolean in the title variable, you will get errors.In the screenshot, you can see that the code editor (Visual Studio Code in this case) gives an errors message specifying that we can only store string values in the variable title.Primitive types include string, number, boolean and if you are not sure about what type of data a variable is supposed to hold, “any” can be used as the type of the variable.The variables, or class members, that are created in the class can be accessed in the template (the HTML file for the same component) using various ways.InterpolationOpen the file src/app/app.component.html, are you will be able to see the use of the title variable like this.The syntax {{ }}  is used to render the values of class members in the view. So now, if you run the application using ng serve --open command, you can see the actual value of the title in the page when the AppComponent is rendered. This is called Interpolation.If you change the value of the title variable and save the file, the development server will automatically refresh the application in the browser.Property BindingProperty binding is the way to binding properties of various HTML elements and components to variables in the class. This allows us to update the UI as soon as the underlying data changes. Let’s have a look at a simple image tag in HTML. We will also remove some unwanted code from the template file of the AppComponent (src/app/app.component.html).We have replaced the default image source with another one which will simply return us a placeholder image which is 500 pixels in width and 300 pixels in height. Let’s save the file and see how the page looks in the browser.As you can see, we get the placeholder image. However, if you notice, the image is constrained because we have also specified a width property on the image tag. So the image width is only 300 px. Let’s bind the width property to a variable in the class and see how it all works.We add an image_width property in the AppComponent class and set its value as 400. Now, let’s set this value as the width of the image in the HTML template.Notice the [ ] syntax. This is called the property binding syntax. Enclosing the property name within the square brackets binding the property to the variable that is provided along.Note: When using property binding, the value provided is evaluated first and then assigned to the property.Since the value of the image_width property is available in the class, the value will be retrieved and will be set as the width of the image. Let’s see how the output looks now.And there you can see that the image is much larger in size because the new width has taken effect. Just like the width property, you can bind all the available properties. Try binding the src property of the image tag and see how it works. You can even try this with different HTML elements and properties.If you are thinking that property binding can be replaced with interpolation, you are right but that is not recommended. So, although the following syntax works, it is recommended to use property binding when dealing with properties.<img width="{{ image_width }}" alt="Angular Logo" src="https://via.placeholder.com/500x300">Event BindingEvent binding allows us to bind methods to DOM events. There are a lot of situations where we may need to get some job done, like accessing an API on the click of a button. We can do that using event binding. Let write a click event on the image element in HTML and bind it to a method in the component class.Enclosing the event name (click in this case) within a pair of parentheses binds the event to the provided expression or method. In this case, we are using a method called displayAlert(). No such method exists as of no now, so we will create the method in app.component.ts file next.w, so we will create the method in app.component.ts file next.As you can see, it is a simple method that does nothing but displays a JavaScript alert to the user. Let’s test everything out.The alert is displayed as you click on the image. All HTML elements have some or other events available that you can bind to. Try using a button element and bind its click event to a method.Two-way BindingNow that we are aware of how we can access the component class data members in the template and use events to invoke methods from the template, let’s have a look at two-way binding where we have a data model that when changed from the template, reflects the changes in the model in the component class and when changed from the component class reflects the changes in the template.Basically, any change to the data (model) from either the template (view) or the component class (controller) is synced. Let’s have a look at how we can this.To implement Two-way binding, we need a special directive called NgModel. NgModel is a special directive. It binds a model to a form field or even an HTML input element. ngModel is special in that it implements two-way data binding. Let’s add the NgModel directive to an input element in our component’s template code.In the above code, we have used the NgModel directive and bound it to a model name. It uses a special syntax. The keyword ngModel is wrapper in a pair of parentheses and then in a pair of square brackets. This is funny, we are using both brackets and parentheses around the ngModel attribute! The idea behind this is intended to invoke is that we’re using both the input [ ] brackets and the output () parentheses. It’s an indication of the two-way binding.A similar property needs to be created in the TypeScript class if we want to access its value in the code (however it is not mandatory). If you save the files now, you will see that you get an error in the browser’s console and the application does not work anymore.Why is that?That’s because the NgModel directive is not part of the core Angular module. It is part of another module called FormsModule. We need to import FormsModule module and bring it into the main AppModule that contains our application. Let’s open src/app/app.module.ts and add the following code. The new code is highlighted in green.First, we are importing the FormsModule and then we are passing it to the imports array so that the AppModule knows about it being a part of the application.Now, save everything, and wait for the application to refresh. You will see that there are no errors and the page looks something like this.Now, that we get the input field and we know that the field is bound to a property or model called name, let’s use interpolation to display the value of the property name on the page.Save all the files and enter some text in the input field in the browser.Woah! Amazing, isn’t it. The changes made to the model are reflected back in the template in real-time. This makes Two-way binding one of the most powerful features of Angular.Two-way binding is used to receive inputs from the user using Forms. This makes sense because NgModel directive is a part of the FormsModule module. We will use it a little more when we learn about Forms in an upcoming module.
logo

Angular JS Tutorial

Angular Basics

Angular is an opinionated front-end javascript framework which means that it enforces a certain style of application development and project structure that developers need to follow to develop apps with Angular. However, it also offers enough flexibility to allow you to structure your project in an understandable and manageable manner.

In this module, we will have a look at some of the most basic concepts that you need to understand before diving into the framework with more advanced concepts.

Components

Angular apps are composed of components. A component is a reusable piece of functionality that can be used throughout the project or even be dropped into other Angular projects. A component has a user-interface defined by the component’s template and the business logic for the component is implemented by the component class. Since Angular is written using TypeScript, all the component class code is written in TypeScript.

Components are the core building blocks of Angular applications. These components are composable which means that bigger components can be formed by using smaller components or that larger components can be broken down into multiple smaller components.

TypeScript is an open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, and adds optional static typing to the language. TypeScript is designed for development of large applications and trans-compiles to JavaScript. Since modern browsers do not understand TypeScript, we need this transpilation process.

Coming back to the project, we created in the last module, if you look inside the src/app folder, you can see a bunch of files there. Let’s have a look at each of these files and understand their role in the Angular project.

Angular Components

In the above screenshot, you can see that there are a total of 6 files as of now inside the src/app folder.

  • app.module.ts: This is the main module file for the project. Each Angular project is divided into modules to make the project management easy. By default, the whole project is a part of a single module but you can always create more modules. A module is a logical chunk of project resources that works independently or in combination with other modules. This file contains a module called AppModule.
  • app.component.html: This file is the template file for the one and only component in our project as of now. This component is called the AppComponent. The extension html indicated that this file is an HTML document and will define the view of the component.
  • app.component.css: This file work in combination with the HTML template and adds CSS styles to the HTML elements defined in that template. This only only contains CSS classes and styles.
  • app.component.ts: This is the main class file for the AppComponent component. This file contains the TypeScript class for the component and all the business logic for this component goes inside this file.
  • app.component.spec.ts: This file is for unit testing the AppComponent component. Let’s not worry about this for now. Feel free to delete the file if it bothers you too much.
  • app-routing.module.ts: This is another module file for the project (just like the app.module.ts that contains the module AppModule) that handles routing or navigation for the whole project. It defines how different components will be presented to the user as the user navigates within the application.

So, it is fairly evident from the above description of the files that a component is composed of 3 files -

  1. The HTML Template
  2. The TS Class
  3. The CSS Styles

Note: Having different files for template, TS class and CSS styles is the convention how components are set up in most applications. However, for simple and small components, you can define the template and CSS styles in the TS class file as well.

Component Lifecycle

Components are core building blocks of Angular applications. Each component is instantiated when it is required, it does its job and then gets destroyed to free us the memory. Component instances have a lifecycle as Angular creates, updates, and destroys them. Developers can tap into key moments in that lifecycle by implementing one or more of the lifecycle hook interfaces in the Angular core library.

Lifecycle hooks allow us to execute our code when the components reach a specific stage in their lifecycle.

For example, we may want to make a call to an external API as soon as a components finished loading or we may want to notify a web-service when a component is destroyed. We can do this with the help of lifecycle hooks.

Here is some of the important lifecycle hooks that Angular provides for the components in the same sequence in which they are called after the constructor of the component class is executed.

  1. ngOnChanges(): called when Angular (re)sets the data bound properties.
  2. ngOnInit(): called after Angular first displays the data-bound properties and sets the directive/component's input properties.  It is generally use to perform complex initializations shortly after construction and to set up the component after Angular sets the input properties.
    You should avoid having these complete initialization logics in your constructors.
    Misko Hevery, the Angular team lead, explains why you should avoid complex constructor logic here.
  3. ngAfterContentInit(): called after Angular projects external content into the component's view / the view that a directive is in.
  4. ngAfterContentChecked(): called after Angular checks the content projected into the directive/component.
  5. ngAfterViewInit(): called after after Angular initializes the component's views and child views.
  6. ngOnDestroy(): called just before Angular destroys the component. This is the time to notify another part of the application that the component is going away.

Classes, Constructors, Variables and Types

Open the file src/app/app/component.ts and there is the code for the TypeScript class responsible for the AppComponent.

Angular code

In the above you can see that we have a class called AppComponent that has a member variable defined inside it. This class does not have a constructor defined, but we can always create a constructor manually as shown below.

Angular code

The code inside the constructor is executed as soon as the class is initialized.

At line#9, a variable is declared named title and is initialized with the value ‘Test’ which is of the type string. Optionally, we can also specify the type explicitly.

title: string = 'Test';

Now, you can only assign values of type string to the title variable. If you try to store a number or a boolean in the title variable, you will get errors.

Angular code

In the screenshot, you can see that the code editor (Visual Studio Code in this case) gives an errors message specifying that we can only store string values in the variable title.

Primitive types include string, number, boolean and if you are not sure about what type of data a variable is supposed to hold, “any” can be used as the type of the variable.

The variables, or class members, that are created in the class can be accessed in the template (the HTML file for the same component) using various ways.

Interpolation

Open the file src/app/app.component.html, are you will be able to see the use of the title variable like this.

Interpolation

The syntax {{ }}  is used to render the values of class members in the view. So now, if you run the application using ng serve --open command, you can see the actual value of the title in the page when the AppComponent is rendered. This is called Interpolation.

Interpolation

If you change the value of the title variable and save the file, the development server will automatically refresh the application in the browser.

Property Binding

Property binding is the way to binding properties of various HTML elements and components to variables in the class. This allows us to update the UI as soon as the underlying data changes. Let’s have a look at a simple image tag in HTML. We will also remove some unwanted code from the template file of the AppComponent (src/app/app.component.html).

Property Binding code

We have replaced the default image source with another one which will simply return us a placeholder image which is 500 pixels in width and 300 pixels in height. Let’s save the file and see how the page looks in the browser.

Angular Basics testing

As you can see, we get the placeholder image. However, if you notice, the image is constrained because we have also specified a width property on the image tag. So the image width is only 300 px. Let’s bind the width property to a variable in the class and see how it all works.

Angular Code

We add an image_width property in the AppComponent class and set its value as 400. Now, let’s set this value as the width of the image in the HTML template.

Angular Code

Notice the [ ] syntax. This is called the property binding syntax. Enclosing the property name within the square brackets binding the property to the variable that is provided along.

Note: When using property binding, the value provided is evaluated first and then assigned to the property.

Since the value of the image_width property is available in the class, the value will be retrieved and will be set as the width of the image. Let’s see how the output looks now.

Angular Basics

And there you can see that the image is much larger in size because the new width has taken effect. Just like the width property, you can bind all the available properties. Try binding the src property of the image tag and see how it works. You can even try this with different HTML elements and properties.

If you are thinking that property binding can be replaced with interpolation, you are right but that is not recommended. So, although the following syntax works, it is recommended to use property binding when dealing with properties.

<img width="{{ image_width }}" alt="Angular Logo" src="https://via.placeholder.com/500x300">

Event Binding

Event binding allows us to bind methods to DOM events. There are a lot of situations where we may need to get some job done, like accessing an API on the click of a button. We can do that using event binding. Let write a click event on the image element in HTML and bind it to a method in the component class.

Event Binding Code

Enclosing the event name (click in this case) within a pair of parentheses binds the event to the provided expression or method. In this case, we are using a method called displayAlert(). No such method exists as of no now, so we will create the method in app.component.ts file next.w, so we will create the method in app.component.ts file next.Event Binding Code

As you can see, it is a simple method that does nothing but displays a JavaScript alert to the user. Let’s test everything out.

Angular Basics

The alert is displayed as you click on the image. All HTML elements have some or other events available that you can bind to. Try using a button element and bind its click event to a method.

Two-way Binding

Now that we are aware of how we can access the component class data members in the template and use events to invoke methods from the template, let’s have a look at two-way binding where we have a data model that when changed from the template, reflects the changes in the model in the component class and when changed from the component class reflects the changes in the template.

Basically, any change to the data (model) from either the template (view) or the component class (controller) is synced. Let’s have a look at how we can this.

To implement Two-way binding, we need a special directive called NgModel. NgModel is a special directive. It binds a model to a form field or even an HTML input element. ngModel is special in that it implements two-way data binding. Let’s add the NgModel directive to an input element in our component’s template code.

Two-way Binding Code

In the above code, we have used the NgModel directive and bound it to a model name. It uses a special syntax. The keyword ngModel is wrapper in a pair of parentheses and then in a pair of square brackets. This is funny, we are using both brackets and parentheses around the ngModel attribute! The idea behind this is intended to invoke is that we’re using both the input [ ] brackets and the output () parentheses. It’s an indication of the two-way binding.

A similar property needs to be created in the TypeScript class if we want to access its value in the code (however it is not mandatory). If you save the files now, you will see that you get an error in the browser’s console and the application does not work anymore.

Angular Basics

Why is that?

That’s because the NgModel directive is not part of the core Angular module. It is part of another module called FormsModule. We need to import FormsModule module and bring it into the main AppModule that contains our application. Let’s open src/app/app.module.ts and add the following code. The new code is highlighted in green.

Two-way Binding Code

First, we are importing the FormsModule and then we are passing it to the imports array so that the AppModule knows about it being a part of the application.

Now, save everything, and wait for the application to refresh. You will see that there are no errors and the page looks something like this.

Now, that we get the input field and we know that the field is bound to a property or model called name, let’s use interpolation to display the value of the property name on the page.

Two-way Binding code

Save all the files and enter some text in the input field in the browser.

Angular Basics

Woah! Amazing, isn’t it. The changes made to the model are reflected back in the template in real-time. This makes Two-way binding one of the most powerful features of Angular.

Two-way binding is used to receive inputs from the user using Forms. This makes sense because NgModel directive is a part of the FormsModule module. We will use it a little more when we learn about Forms in an upcoming module.

Leave a Reply

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

Comments

somasundarapandian

great learning blog!

michael

great blog!

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