Google+
Shineyrock web design & consultancy

Shineyrock

blog

  • dislike -6 03

    Creating Your First Angular App: Basics

    Angular has become very popular over the past few 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 then there's Angular 2+, which is version 2. AngularJS is no longer supported, and there are many differences between the two versions. 

    Should You Use Angular? 

    This is one of the first questions you must ask, and the answer is: it 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 TypeScript, 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. 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 handle most routine tasks for you. This is why you must install the CLI to start with Angular. You can install the Angular CLI by running the following command.

    Now, you can create a new Angular app by running the following command in 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 a correctly 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 in the template.

    home page of country information apphome page of country information apphome page of country information app

    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.

    "all countries page" of our app"all countries page" of our app"all countries page" of our app

    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. 

    After the details of each country, there is a back button which 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.

    country details with back buttoncountry details with back buttoncountry details with back button

    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 that already exist in 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.

    folder structurefolder structurefolder structure

    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:

     Angular 12 architecture  Angular 12 architecture  Angular 12 architecture

    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. At first, 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:

    All the components that we create will have a custom selector which specifies the tag that renders the component in 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 use *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 an action or value. This kind of push or pull logic is error-prone and tedious. Above all, it can be a nightmare to handle it all 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 a component is shown below:

    flow of control between the DOM and a componentflow of control between the DOM and a componentflow of control between the DOM and a component

    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 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 the 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 of two-way data binding. 

    In two-way binding, data flows to the input box from the component with property binding. 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 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 are crucial topics in the Angular Framework. As you build the country application, in our upcoming tutorials, you will understand their importance. 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 the different components that we will create as parts of that car, like the engine and the wheels. Each component will perform a 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. Then 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 half a decade of experience. She is a grad and gold medalist from Anna University.

    martijn broeders

    founder/ strategic creative at shineyrock web design & consultancy
    e-mail: .(JavaScript must be enabled to view this email address)
    phone: 434 210 0245

By - category

    By - date