Where should I learn AngularJS from

Angular tutorial for beginners

introduction

This tutorial explains the basics of the Angular framework. We are dealing with Angular version 2 and higher. However, the version number is deliberately left out because the framework now uses semantic versioning. In short, it's just Angular.

This introduction is intended for beginners who are just starting out with Angular. The example is based on the first tasks in our workshop content of the Angular Intensive Training.

Our didactics deal with motivation, theory and then the practical part. You can program all the tasks yourself and receive help and sample solutions for the tasks via our Workshops.DE Classroom.

What will you learn in this tutorial?

This tutorial shows you the basic components of an Angular application using a practical example, which you can implement yourself or use and change with ready-made sample solutions.

We will deal with the following topics:

  • What is Angular?
  • Differences to React and Vue
  • Installation of Angular
  • Components
  • Expressions and loops
  • Event & property binding
  • Services
  • Dependency injection
  • Connect a rest API

We will briefly introduce the motivation and the theoretical background, but focus primarily on practical examples. We will build a small application that will read a list of data from a REST API and display it.

This article and our portal are open-source. If you have any suggestions for improving the article, feel free to participate via our GitHub repo at any time. We look forward to every input!

What is Angular?

Angular is a very successful, client-side JavaScript web framework for creating single-page web applications. It joins the other large frameworks for single page applications. Although that's not entirely true, since Angular has actually evolved into a platform in the meantime. In addition to the pure “API” for application development, it now also includes development tools, generators and the supplied architecture concepts and thus represents a ready-to-rock solution for developing enterprise applications. It joins the other two successful front-end frameworks React and VueJS.

Differences to VueJS and React

All three libraries, or frameworks, have their raison d'être, strengths and weaknesses. Depending on the use case, a decision should be made here as to which of the alternatives provides the best basis for the current project.

Angular clearly aims at the professional development of enterprise software. With clear specifications in the structure and the use of generators, long-term maintainable and scalable software solutions can be created. Concepts such as dependency injection and a focus on TDD have been anchored in the core of Angular since the very beginning. Due to the clear structure of projects, the scalability of new developers should be emphasized. Due to this massive framework, Angular often looks a bit heavy at first glance - but convinces in production through systematic optimization and expandability.

ReactJS aims at a very minimal layer on the component level and enables / requires the design of your own architecture from scratch. This offers very flexible possibilities to build very explicit solutions for individual problems. There is a selection of different modules for different requirements. The effort of integration and maintenance is higher here than in Angular, but this often also makes the project simpler and very lightweight.

VueJS serves the requirements between these two frameworks. By relying on a generator and clear structures, the framework also favors the scaling of project teams. However, VueJS tries at the same time to remain very lightweight and to bring in as little “framework magic” as possible. So it is the simple but structured middle solution.

This is my personal assessment and I have worked very well with all of these frameworks. It depends individually on the problem and the team. If you are new to the web, I can also highly recommend our Modern Web Development and Frontend Architecture Course, which gives you an overview of today's modern web development.

motivation

Angular itself has its origins in 2009, in the “wild west” of web application development. A lot has happened since then - don't worry, I'm not going to start a history lesson here. It's more about this point: How was Angular able to prove itself to be one of the most successful frameworks in the wild world of JavaScript frameworks, in which it seems like 10 new frameworks appear every day? Perhaps the easiest way to describe this is by using Angular's mission:

  • Apps that users ❤️ to use.
  • Apps that developers ❤️ to build.
  • A community where everyone feels welcome.

This mission has created a wonderful ecosystem with an amazing community. But the focus on quality and enterprise can also be clearly felt. Google says it uses Angular in over 1,600 projects. (Incidentally, Google Teams ALSO use React and VueJS for projects where this stack fits better).

In 2016 the Angular team decided to do a complete rewrite in TypeScript. Back then, the decision was largely negatively perceived and torn apart by other framework users.

Today we see the foresight of these decisions, as many other frameworks now also rely on TypeScript. In order to be able to communicate breaking changes more easily, the team has also decided on a fixed release plan. In this way, project teams can plan budgets for updates in advance and are not “surprised” by breaking changes in a release.

The Angular platform

Angular's ecosystem is very large. The basis for this is the core framework. The fundamental concepts that are essential for modern web applications are implemented here. Two further core concepts, which can be used separately, are the Angular CLI and the management of components. These form the core functionalities that are required in almost every application. Further modules can be optionally includeif you need these:

  • Routing - Routing for single page applications
  • forms - forms and validation
  • i18n - Multilingual Applications
  • Animations - animations for transitions
  • PWA - offline skills
  • HTTP - HTTP, REST and GraphQL communication
  • and many more

In this tutorial we will primarily take care of the framework, the Angular CLI and components.

Preparation & installation

Now let's start installing NodeJS. NodeJS is the so-called “JavaScript Runtime” and is responsible for executing programs on our computer that are written in the JavaScript language, such as the Angular command line interface, which we will use shortly.

You can download and install NodeJS via the following link: https://nodejs.org/download/

The command line tool is also installed with NodeJS, which enables us to install additional NodeJS packages on our computer.

After you have successfully completed the installation, you can now execute the following command on your terminal:

npm i -g @ angular / cli bookmonkey-api

This command installs the globally on your computer and thus enables you to work with the command line tool after the installation. The second package installed is the package that we use as a simulated backend server in our example.

Generate the Angular App

The Angular CLI is used to generate new structures within our applications, instead of copying the basic structures as is often the case in projects and stumbling over potential errors when renaming. It is a powerful tool that offers you a detailed help text.

To generate our first application, we use the command, which takes the name of your application as an argument. You will be asked if you want to install this: No. Furthermore, which stylesheet format you want to use: Please choose SCSS.

In this tutorial we will not use the strict mode of Angular and TypeScript so that we can focus fully on the Angular features.

If you use the Angular CLI later to generate code or to execute the project, the CLI asks whether you want to make your usage data available anonymously in order to improve the Angular CLI.

The project structures are now automatically created for you. This includes a start page, a component, the first End2End tests, linter rules, GitIgnore rules and a TypeScript configuration.

After generating, the necessary packages are also installed via. This can take a few minutes. Once the installation is complete, you can start the development environment.

Your basic application has now been generated and can be called up in the browser at http: // localhost: 4200. You should see a picture similar to this:

Components and Services

In Angular there are two primary parts of the framework that we will deal with first.

Components are display elements. They are defined as their own HTML elements. Depending on the defined display logic and the current data, these elements represent the status of the application.

Services are independent of the display of your application. They define the data, logic and algorithms of the application. They are modular and reusable.

Components

Angular components are the so-called “building blocks” of any application. The various logical building blocks of an application are divided into components. Each of these components has a specific function and is defined as a separate HTML element.

Note: This representation is not yet 100% correct and is used in a simplified form for step-by-step explanation. 🙂

As you can see in this small example of a ToDo list, there are separate elements for the various areas, which in this case are introduced with the prefix. As you can see from the, it is possible and also absolutely common to nest your own components within one another. The aim is to build reusable and maintainable elements over and over again. You will have to decide for yourself in your projects what the correct component size is, and with increasing experience you will get a better and better feeling for it. If you are unsure, you can also contact us at any time in our Discord.

Services

For data and logic that are not necessarily linked to just one component, Angular Services are used. A service is a class that defines attributes and methods that can be used by components and other services.

The actual data is therefore referenced from a service, because other components may also be displayed on the basis of the current to-dos, such as a component that counts the currently open to-dos.

This should suffice as a first overview at this point. We'll take a closer look at Services later.

The first component

If we now look at the component definition, we come into contact with TypeScript for the first time. TypeScript is an extension of JavaScript, which allows us to explicitly type the data in our application. Furthermore, this meta-language also introduces features that do not (yet) exist in JavaScript, such as. TypeScript “transpiled” our written source code so that the browser can see and interpret normal JavaScript again afterwards. So it's a feature that makes our day-to-day work more pleasant for us as developers.

Classes were introduced in ES2015 so that concepts such as inheritance and constructors no longer have to be mapped using prototypes. These can now be created using a simple and clean syntax.

Decorator are structured metadata of a class. You may know this from other programming languages ​​such as Java. We map the actual functional behavior of the component within the class with methods.

A component definition primarily consists of the following parts:

  • One Component decoratorwhich makes the component known within Angular.
  • One Selectorwhich describes the HTML element that we create.
  • One HTML templatewhich defines the representation of our component.
  • One classwhich describes the interface and the display logic of the component.

Our first component will be a static info box. To generate this, we use the Angular CLI again. You can open a new terminal or stop the current one for a short time. The serve process automatically detects changes within your source code and compiles the current version of your application in a few seconds. So I would recommend you to open a second terminal and use the following command:

The files that are currently relevant to us are currently and our template. First of all, let's take a look at our class.

Here we see a component as expected. Our selector got the automatic prefix. Our new component can now be used under the HTML tag. The entry point of our entire application is also a component with the name. In order to display our freshly generated component, we have to call it up in the template of our application. To do this, go to the file, delete the entire current content there and insert your component via HTML tag.

If you now open your application in the browser again, you should see the output. At this point you are welcome to play around with your template and also create several of these info boxes by simply copying the HTML tag in your app template. A historic moment - take a few seconds to admire your first component. 😉

Expressions

A component with static content can of course only be used to a very limited extent in an application. To display variable data, Angular uses so-called expressions in the templates. These are introduced and closed again with double curly brackets.

{{expression}}

An expression is dynamically evaluated by Angular based on the current properties of your class. So if we introduce a new property and fill it with a string, we can output it in our template.

Should the property change, e.g. B. by external events, this is automatically updated by Angular. This concept is called.

Property & event bindings

Other components can be integrated via so-called property and event bindings. Angular combines with the properties and events of the native HTML elements. This also makes it easy to use other elements from frameworks such as ReactJS or VueJS.

To access properties of elements, we use the square brackets within our HTML template. For example, if we want to influence the HTMLElement.hidden property of a component, we can do this as follows:

Here the property of the element is set to and thus the element is hidden. In order to change this property dynamically, we have the option of introducing a new property in our class ourselves and binding it to the property of the p element via. To do this, instead of the string, we set the name of the attribute in our class to the binding:

In order to change the component through user interaction, we have the option of listening to so-called and also defining one for this. Event bindings are defined in Angular using round brackets, which contain the name of the event. So if we want to listen to the click event of an HTML element, we can do it as follows.

Within this definition, we now have the option of defining a so-called one. This can be one that z. B. makes direct changes to attributes of your class as well as a reference to a method in your class. To keep it simple, let's first use one that negates the value of in this case. So it turns out and vice versa.

Of course, we can also organize any other event, such as B. use. With this very simple mechanism we can generically use and interact with all kinds of components. This is independent of whether they are written in Angular or another framework.

Loops with * ngFor

As in every framework, another core feature is the output of list-like data structures. There is a directive in Angular for this.

Directives are HTML attributes that can be used on DOM elements. Here we can differentiate between and. Attribute directives change or influence the behavior of an element to which they are attached, e.g. B. for setting CSS styles based on data. Structural directives create or remove DOM elements such as or. Structural directives are identified with the prefix.

The directive is based on a for loop, iterates over a list-like structure and creates a copy of the DOM element to which it is applied for each element.

Here a so-called, in our example, and a list, in ours, is defined.The variable book thus contains the value of the current list entry.

To try it out, we create a new component with the Angular CLI. To do this, we execute the command. So that the component is displayed in the browser, we insert the tag in the template of the. So if we in the (see book-list.component.ts) define a variable with a list of books, we get 3 DOM elements for this.

The first service

If you paid close attention, you noticed that the data in an Angular application does not belong in the component. We mix the display logic with the management of our data. So let's do a quick refactoring of our application and extract the data into a separate service.

A service should always take care of an explicit task and be named accordingly. In our case we want to manage the data of books. So we call our service. To generate this, we can use the Angular CLI as usual.

So we pulled the data from our component. The only question now is: How do I get the data connected back into my component? This is where the term comes into play.

Dependency injection

One understands a design pattern, which is also mentioned. The point here is that the required dependency is not generated by the calling point itself, but that this component transfers control and only defines which dependencies exist.

In our small example, it does not create our service, but just notifies the Angular Framework that it needs one in order to work.

Note: This is a very simplified representation of Dependency Injection in Angular to understand the basic concept.

Within the Angular Framework, the various services are managed by the so-called. This gives the calling point a reference to the requested service, if this is defined.

The definition of the dependency is mapped using the constructor. In our example, we define the dependency and bind it to the field of our component.

Note: We are using TypeScript typing here by writing `: BookDataService` after our variable. This means that the variable `bookData` has the type` BookDataService` and is essential for the dependency injection mechanism. In the other parts of this tutorial we have not used typing in order to keep the complexity of the tutorial as low as possible.

We then call the service method within the constructor and obtain our data.

Most of the time your IDE imports it automatically. If this is not the case, you can do this yourself and write the following import at the beginning of the.

Reload data via Rest-API

The current version has explained the concepts of Angular to us bit by bit. In reality, however, data is usually reloaded asynchronously from a server.

We load this data from an example API, which you can start with the following command:

You can now view the data that is output by the server under the following URL: http: // localhost: 4730 / books

In the next step we want to access this data from our own. For this we need the so-called service. This offers us a very simple API to perform various operations on an HTTP interface.

The service is part of a separate module and must be explicitly integrated. We achieve this by importing this in the file and specifying it in the array.

If this is done, our also knows a service of the type, which we can now integrate via our constructor.

The service offers us the method to which we can specify the API endpoint for our query. We use the address of the locally started JSON server here.

Dealing with asynchronicity

The return value of the get method of the HTTP service returns an observable. This is a data structure that makes it easier for us to deal with asynchronous data. Angular uses the RxJS Observables for this.

It has established itself as a good style to mark variables and fields that hold asynchronous data structures with a postfix. It has no functional impact, but helps you find your way around and maintain your application in the long term.

Most of the time your IDE imports it automatically. If this is not the case, you can do this yourself and write the following import at the beginning of the.

Basically, the call within our component does not change. However, the evaluation within our HTML template has to be adjusted a little. With the help of a so-called pipe, we can enable the directive to handle the asynchronous data structure.

The pipe in connection with registers for asynchronous updates of the variable. By adapting our template, we can now also display the data from our JSON server as follows:

Conclusion

Angular is very opinionated in many ways. This means that many decisions about architecture and rendering are already made for the developer. This of course has the advantage that the project team can concentrate 100% on the implementation of features and does not have to build the basic architecture independently.

Due to the very uniform structure of Angular applications, developers trained in Angular can be integrated very quickly into the project, as Angular applications always follow a certain structure. This makes the scaling of developer time on the project much easier than with individual solutions of the architecture in other frameworks.

In general, it is certainly a good option for long-lasting enterprise projects. However, other frameworks such as React and VueJS should also be considered in order to objectively make the best decision for the current challenges.

If you want to continue exchanging ideas with us and others, join our Discord Chat with over 2000 wonderful other people! It's better to learn together! :)


Did the tutorial help you?

We also offer Angular and TypeScript training courses to guide you as effectively as possible on the subject of Angular. In the course you can ask the questions that you can hardly google, e.g. "Better way to structure my application". We can answer them for you.