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.
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.
In the above screenshot, you can see that there are a total of 6 files as of now inside the src/app folder.
So, it is fairly evident from the above description of the files that a component is composed of 3 files -
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.
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.
Open 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.
Open 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 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 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.
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.
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.
great learning blog!
great blog!
Build various types of web applications,command-line application,etc....
JavaScript is a dynamic computer programming language for the web. Jav...
Leave a Reply
Your email address will not be published. Required fields are marked *