Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 13, 2022 04:18 am

Creating Your First Angular App: Basics


Angular has become very popular over the past couple of years. You can use this open-source JavaScript framework to build web and mobile apps. If you've been thinking about learning Angular but don't know where to start, following this series might be a good idea.


The aim of this series is to cover the basics of Angular while creating a very simple app that shows information about different countries. Angular is written in TypeScript, so it makes sense that you write your own code in TypeScript as well. 


Getting Started


If you are already familiar with TypeScript, you can just go ahead and start creating your first Angular app. Remember, there are two major versions of Angular Framework. One, is AngularJS which is version 1. And, Angular 2+ which is version 2. AngularJS is no longer supported, and there are many differences between both the versions. 


Should You Use Angular? 


This is one of the first few questions you must ask. And, the answer to this question depends. Some developers will argue that React is better. But, there are problems in React too! A strength of Angular is that it is an integrated framework which allows you to build projects without thinking a lot about libraries. 


If you want to try Angular, the first step is to install Node.js. You can then head to the official website and download the appropriate version. The Node Package Manager npm will be installed as part of Node.js.


TypeScript


The next step is to install TypeScript by running the following command. If you are not familiar with YypeScript, don't worry. A little bit of knowledge in JavaScript is more than enough. To put it simply, TypeScript is just typed JavaScript with additional features. And, many modern editors are useful in helping you master TypeScript. I have also written a series titled TypeScript for Beginners on Envato Tuts+, where you can learn the basics of TypeScript first.



Angular CLI


The Angular Framework comes with its very own Command Line Interface (CLI). The CLI will do most of the routine tasks for you. This is why to start with Angular, you must install the CLI. You can install the Angular CLI by running the following command.



Now, you can create a new Angular app by running the following command inside the terminal. Before running the command, make sure that you have moved to the directory where you want to create the app.



Installing all the dependencies for the project takes some time, so please be patient while Angular CLI sets up your app. After the installation completes, you will see a folder named country-app in the current directory. You can run your app right now by changing the directory to country-app and then running ng serve in the console.



Adding --open will automatically open your app in the browser at https://localhost:4200/.


You will see the below screen, when you run the application for the first time, without making any changes to the code. So, what just happened? Angular CLI runs a Webpack dev server. The Webpack Dev Server renders the application on port 4200. It also watches for changes in the project source code. With every change, the code recompiles and the browser reloads. Since you are using Angular CLI, you are already working in the rightly configured development environment. So, you don't need to do anything but get started on the project.


Angular screen Angular screen Angular screen

What are we going to build?


Country Information App Overview


The country information app that we are creating will have three components. The HomeComponent will show the top three countries under various categories like population, GDP, and area. You will be able to click the name of each country to read more about it. The additional information about the country is listed using another component, which we will be calling the CountryDetailComponent. There will be one more component in our app, which will be used to display a list of all the countries that we have stored in our app. 


Since this is your first Angular app, our main aim will be to keep things simple without adding any complicated functionality. Once you have a good grasp of the basics, creating more complex apps will not seem like a daunting task.


The image below is of the homepage or HomeComponent in our country information app. As you can see, there are three countries under each category, and they have been placed in descending order. While creating the HomeComponent, you will learn how to sort different countries before displaying them inside the template.



The following image shows the "all countries page" or AllCountriesComponent of our app. The layout of this component is very similar to the HomeComponent. The only difference is that this time we are listing all the countries along with their capitals.



If you click on the box of any country rendered inside either the HomeComponent or the AllCountriesComponent, you will be taken to the country detail page or CountryDetailComponent. The information provided about a country is not editable. 


There is a back button after the details of each country. This back button takes you back to the previous component or page. If you came to the CountryDetailComponent from the HomeComponent, you will be taken back to the HomeComponent. If you arrived at the CountryDetailComponent from the AllCountriesComponent, you will be taken back to the AllCountriesComponent.



Referring to different components that we are creating as pages is not technically correct. However, I am using terms like homepage or HomeComponent interchangeably because seeing a lot of unfamiliar terms like routing, components, and decorators can be intimidating for readers who have never created an Angular app before. Using these terms loosely for this series can help you learn quickly instead of getting confused by the jargon.


Angular Basics


Application Shell


After you run the ng new country-app command, the Angular CLI creates a bunch of files and folders for you. Seeing so many files can be intimidating as a beginner, but you don't need to work with all those files. When creating our country app, we will only be modifying the files already existing inside the src/app folder as well as creating new files in the same directory. Right now, you should have five different files in the src/app folder. These files create an application shell which will be used to put together the rest of our app. In Angular 12, the folder structure appears as below. 


The way your Angular folders are structured is important. A good folder structure makes code maintenance simple, and seamless. We have a great free course to help you understand and implement better folder structures.



The Technical Details


Before we begin creating our app, you need to be comfortable with the basic concepts of Angular. This section will very briefly cover important topics like components and templates. And, the goal of this post is to help you get accustomed to these!


In Angular, regardless of the version, you have a few major building blocks:



  • modules

  • components

  • templates

  • metadata

  • data binding

  • directives

  • services

  • dependency injection


You can see how these pieces of the Angular 12 architecture fit together below:



What are Modules?


Since Angular 2+, Angular has focused on maintaining modularity. This is why we have Angular modules, also called NgModules. Every Angular application you create will have at least one Angular module: the root module. In general, these are known as the AppModule. In the beginning, your application will have only the root module. With time, you will end up creating multiple modules to define the workflow, or capabilities of a specific application domain.


Remember, every Angular Module is a class which contains the @NgModule decorator. 


Decorators are functions written to modify classes in JavaScript. Decorators are used to link metadata to classes. This metadata gives details on how a class should work, and how it should be configured.


Here's an example of metadata for an AppModule:



What are Components?


Components are the building blocks of an Angular app. They allow you to control the UI of your app. A basic component consists of two parts: a decorator and a class definition. You can specify the application logic for a component inside the class. 


The component decorator is used to specify information like a custom selector to identify the component, the path to the HTML template, and the style rules to be applied to the component. 


Here is a basic component decorator that sets all three values for



All the components that we create will have a custom selector which specifies the tag that renders the component inside the browser. These custom tags can have any name you want. For example, we will be creating a countryDetailComponent in the third tutorial of the series, and we will use our own custom tag called app-country-detail to render this component in the browser.


This is just the beginning, we also have an in-depth guide to Angular Components.



What are Templates?


Templates are companions to Angular Components. In very simple terms, the template is nothing but an HTML snippet. It tells how a component should be rendered. In our HomeComponent the template appears as below. 



It is regular HTML with a few differences. For instance, we make use of *ngFor to loop through arrays and render in the view. 



What is Data Binding?


When you don't have a framework, data values should be pushed into HTML controls, whenever a user responds with some action or value. This kind of push or pull logic is error-prone, and tedious. Above all, it can be a nightmare to handle them manually. This is why the Angular Framework offers Data Binding


By definition, data binding is a mechanism for coordinating the template and components. The overall flow of control between the DOM, and component is as below:



As you venture into the Country Application, you will see a couple of places where button click events are captured, and changes in the view reflect on the business logic. You will find the below pieces of code:


An example of event binding:



An example of property binding:



Likewise, The app.component.ts file contains the logic for our component written in TypeScript. You can open this file and update the title property of the AppComponent class to 'Fun Facts About Countries'. The app.component.ts file should now have the following code. 



The app.component.html file contains the template for our AppComponent class. Open the app.component.html file and replace the boilerplate HTML code inside it with the following line:



By wrapping title inside the curly brackets, we are telling Angular to put the value of title property of the AppComponent class inside the h1 tag. 


Two way data binding is a crucial part, as it combines both event and property binding into a single notation. This is nothing but the ngModel directive. Here is a simple example for two way data binding. 



In two way binding, data flows to the input box from the component with property binding. And, when the user changes a value, data flows back to the component with event binding. In Angular, all data bindings are processed only once per JavaScript event cycle. 


Data binding plays a crucial role in Angular forms. Whether it is reactive, or template driven forms, you need two way data binding. We have a tutorial where you can learn more about two way binding, and Angular forms


What is a Service?


Different components of our app will need to retrieve the data to display on screen. We will be creating a service class that will contain functions to help us retrieve this data and sort or modify it one way or another. We will then use the functionality of different component classes to display this data to the user.


You can consider a Service to simply be any value, function, or feature that your application needs. Getting all the countries stored inside our application is a service, and so is sorting and displaying them. All the three components in our class will be using functions from our service to retrieve data. 


Here is a code snippet from the country-app that we will be creating. As you can see, we are importing Component and OnInit from the @angular/core. Similarly, we are importing a Country and CountryService from files that we created ourselves.



Services and Dependency Injection is a crucial topic in the Angular Framework. As you build the country application, in our upcoming tutorials, you will understand its importance. And, if you wish to learn all the internals of an Angular service, check out our beginner's guide to Angular services



Running the Application 


The changes made to this file will be automatically reflected in the browser at http://localhost:4200/. Just make sure that the console is still open and you have already typed in the ng serve command from the beginning of the tutorial. 


Different functions and features of the app will be controlled by multiple simpler components that we will create later. You can think of this application shell as a car and different components that we will create as parts of that car like the engine and the wheels. Each component will perform its specific function, and you can put them all together to create the whole car.


Final Thoughts


The aim of this tutorial was to help you install all the necessary tools that you need to create an Angular app and quickly go over some fundamental Angular concepts.


To summarize, you need to know the basics of TypeScript before you can create an Angular app. In the next step, you need to install Node.js, TypeScript, and the Angular CLI. After that, you can just run the npm commands from the Getting Started section of this tutorial, and your first Angular app will be up and running.


Our country app will do a lot more than just show the title. In the next tutorial, you will create a few classes and services that will be used to store and retrieve data about different countries. These classes and services will be useful in the third and fourth tutorials, where we will create different components of our app.


This post has been updated with contributions from Divya Dev. Divya is a front-end developer with more than a half a decade of experience. She is a grad and gold medalist from Anna University.



Original Link: https://code.tutsplus.com/tutorials/creating-your-first-angular-app-basics--cms-30092

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code