DEV Community

loading...
Cover image for AngularJS tutorial: How to build your first app
Educative

AngularJS tutorial: How to build your first app

ryanthelin profile image Ryan Thelin Originally published at educative.io ・10 min read

Front-end frameworks define modern web development work due to the capabilities of their simple yet powerful components. Angular.js stands out from other frameworks by offering developers the most control over every detail of their app.

While more difficult to pick up than React, Angular's extensive tools and advanced features have made it a favorite for companies like Google and Amazon.

Today, we'll help you get started with Angular.js, break down the essential elements of any Angular app, and walk you through the creation of your first Angular web application.

Here’s what we’ll cover today:

Master Angular.js in half the time

Learn Angular.js fast using skimmable, hands-on courses.

A Hands-on Guide to Angular

Alt Text

What is Angular.js?

Angular.js is a JavaScript framework used to build client-side applications with CSS, HTML, and JS. The primary building block of any Angular application are components with collections of code to execute specific behaviors.

Angular lets you use HTML as a template language and extend HTML's syntax as you build components. AngularJS framework works by reading the HTML of a page and interpreting the attributes as directives to bind the page to a model based on standard JavaScript variables.

Angular is beloved by frontend developers because it streamlined app creation with ready to use packages for common services, preview browser templates of code, back-end integration, and features like expressive HTML.

While not as beginner-friendly as other frameworks, Angular is the most mature JS framework on the market with years of complete packages for you to take advantage of.

Angular's user base is still growing and has been long adopted by companies like Google and Amazon. As more companies adopt Angular each day, 2021 is a great time to join the Angular.js community.

Key features of Angular

  • MVC architecture (Model-View-Controller): Separates program components into buckets of Model, View, and Controller to separate the presentation layer from the business logic.
  • Two-way Data Binding: Angular automatically synchronizes your HTML view with your code, allowing you to watch your view update to changes in real-time.
  • Routing Support: Easily build single-page applications (SPAs) that provide a desktop experience when navigating across views.
  • Dependency Injection: Allows code dependencies to be automatically injected with a dependency container, so no main() method is required.
  • Form Validation: Improve user experience in CRUD applications with Angular's easy-to-implement form validation.

Angular.js vs React

The main competitor to Angular.js is Facebook's React framework. Each has its own advantages, disadvantages, and different design philosophies that define when they're used. Let's break down the primary differences to see where Angular shines.

Alt Text

React

React is designed to be lightweight and beginner-friendly but lacks the in-depth control possible with Angular.

Advantages

  • Offers a simple JS design using a syntax that combines HTML and JavaScript. React also offers great documentation for initial learners. *React’s Virtual DOM implementation and rendering optimizations make it very fast
  • Top-notch Progressive Web App (PWA) support, especially with its create-react-app template generator.
  • Built for reusable and modularized code. This makes apps easier to maintain and build upon, allowing for complex infrastructure to be more easily developed and scaled.

Limitations

  • React is a highly un-opinionated technology, which means that developers have to make their own design choices.
  • React technology is constantly updating, so it can be difficult to keep with the latest documentation.
  • React relies on JSX, which can be a learning barrier to some newer developers.

Alt Text

Angular.js

Angular is built with the opposite of React: maximize control at the cost of beginner-friendliness.

Once you master Angular, you have the tools to control and fine-tune every aspect of your app in a way you couldn't with React.

Advantages

  • Angular is supported by Google, with detailed documentation and a large community. There are numerous high-quality resources provided to help you learn quicker.
  • Angular-language-service speeds up development with advanced coding features like autocomplete for external HTML template files.
  • Advanced MVC architecture for better division of responsibilities and code organization.
  • Supports test-driven development with instant code-to-view updates and tools for both end-to-end and unit testing.

Limitations

  • Harder to learn than React because Angular offers a variety of different structures like Injectables, Components, Pipes, Modules, and more. It takes time to learn the place for each of these structures rather than learning just components to React.
  • Slower performance by default because it works with the real DOM. Requires additional work to perform as fast as React, such as manual control of the rendering process.

For more on the differences between Angular and top frameworks Vue and React, see our previous article: Angular vs Vue vs React: choosing the best framework in 2020

Getting familiar with Angular elements

To understand Angular, you need to break down an application into its different elements and understand how they interact.

Alt Text

Angular.js apps have collections of alike components called Modules. Components are a special type of Directive that decides the behavior of a particular UI element. Components reference each other and back-end resources using connectors called Services.

Finally, all this code is automatically displayed in real-time from Model to View components using Data Binding.

Modules

Modules are containers of similar components, directives, and pipes that all relate to the same functionality. These modules can be imported and exported all at once, allowing for easy reuse across the app. Each component can only be a part of one module.

Think of Modules as a hybrid between classes and containers.

Here's an example of an Angular Module:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {FormsModule} from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AssessmentsModule } from './assessments/assessments.module';
import { CoreModule } from './core/core.module';
import { SharedModule } from './shared/shared.module';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule, AssessmentsModule, CoreModule, SharedModule, FormsModule, BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Enter fullscreen mode Exit fullscreen mode
  • The bootstrap array contains the first component that will be initialized and rendered with the startup of the Angular application.
  • The declarations array contains a list of components, pipes, and directives that are defined in the module.
  • The imports array contains all the modules that our app will import from other libraries or Angular modules.
  • The exports array allows us to share components, pipes, or directives from this module to others.

Components

Components are the most basic building block for any Angular application. Each component controls a section of the user interface called a view.

These components can have dynamic elements defined in the component's class that respond to events like clicks or hovering over.

Components are updated, created, and destroyed as the user navigates through the application.

Here's what a component looks like:

@Component({
  selector: 'app-child-one',
  templateUrl: './child-one.component.html',
  styleUrls: ['./child-one.component.scss']
})
export class ChildOneComponent{ }
Enter fullscreen mode Exit fullscreen mode
  • The selector sets the name of the component. Modules and directives use the name to reference this component.
  • The templateUrl attribute declares which HTML file this component will reference for its behavior. You can also create an inline HTML template using template: followed by your code.
template: `
<h1>Hello from App Component</h1>
`

Enter fullscreen mode Exit fullscreen mode
  • The stylesUrl attribute declares which CSS file this component will reference. As above, you can also inline your CSS style using:

styles:['div { font-weight: 600; }']]

Directives

Directives extend the behavior of any HTML element. The behavior is often things like a change in layout or appearance. Apart from Components, there are two other main types of directives.

Attribute directives

These directives help us extend the behavior or appearance of the elements inside the template. The most commonly used attribute directive is NgStyle, which allows you to change the style of several elements at once.

Structural directives

Structural directives are the most widely used directive in Angular apps. These directives help us work on the layout of the data, for example looping through it, applying conditions on the data, etc. The convention for a structural directive uses an asterisk (*) before the directive name.

The commonly used structural directives are *ngFor and *ngIf.

  • *ngFor acts as a for loop that allows us to loop through an array:
<table class ="table table-striped" >
  <tr *ngFor="let u of users">
    <td>
      {{u.id}}
    </td>
    <td>
      {{u.name}}
    </td>
    <td>
      {{u.model}}
    </td>
  </tr>
</table>
Enter fullscreen mode Exit fullscreen mode
  • *ngIf acts as an if statement for conditional rendering of data:
<div *ngIf="showElement">
  <div>This element is based on the showElement condition</div>
</div>
Enter fullscreen mode Exit fullscreen mode

Services

Components need Services to fetch data to display. This data can be directly from the backend or another unrelated component. You can think of services as the couriers that connect components to their data source.

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class ExampleService {
  constructor() { }
}
Enter fullscreen mode Exit fullscreen mode

Services use Angular's dependency injection system to track which classes (export class) depend on which data sources (providedIn).

Keep learning about AngularJS.

Learn the Angular.js skills you'll need at your next interview. Educative's text-based courses are easy to skim and give you live, hands-on practice with today's most demanded skills.

A Hands-on Guide to Angular

First Angular.js Application

Now that you've seen Angular.js' structure, let's get you some hands-on experience and build our first Hello World program.

Installing Angular

Before you get started, you'll need to use the command line to install Angular. You'll also need an updated version of Node.js and npm package manager.

First, install the Angular CLI by entering the following command into your terminal window:

npm install -g @angular/cli
Enter fullscreen mode Exit fullscreen mode

The CLI allows you to create projects, generate application/library code, and implement tasks like testing and deployment.

Next, you'll need to create an Angular workspace and initial application.

In your terminal, enter the CLI command:

ng new my-app
Enter fullscreen mode Exit fullscreen mode

You'll be prompted to enter information about the new app, but for now, simply accept the defaults.
Finally, find the newly created workspace folder my-app and run these commands:

cd my-app
ng serve --open
Enter fullscreen mode Exit fullscreen mode

This will set up a responsive local app server and open it in your browser to localhost:4200. The webpage will provide several resources to continue learning or options like + New Component that will get you developing.

Hello World

Now that you have Angular installed, you're ready to write your first Angular.js application.

We'll make a greeting app that asks a user's name to greet them with, then says "hello, [name]".
Below is the starting point of our program, a mostly bare HTML document. We'll build out our app step by step from here.

<html>
   <head>
      <title>AngularJS First Application</title>
   </head>

   <body>
      <h1>Sample Application</h1>
   </body>
</html>
Enter fullscreen mode Exit fullscreen mode

1. Define AngularJS application using ng-app directive

<div ng-app = "">
   ...
</div>
Enter fullscreen mode Exit fullscreen mode

This will define and link your Angular app to the HTML file.

2. Define a model name using ng-model directive

Within the previously made div section, enter:

<p>Enter your Name: <input type = "text" ng-model = "name"></p>
Enter fullscreen mode Exit fullscreen mode

ng-model creates a model variable called name within our AngularJS application and binds it to take HTML input. In other words, it tells your Angular app to pull data from the HTML document.

3. Bind the value of the above model defined using ng-bind directive

In the same div section, now write:

<p>Hello <span ng-bind = "name"></span>!</p>
Enter fullscreen mode Exit fullscreen mode

Then, close div using:

</div>
Enter fullscreen mode Exit fullscreen mode

This will bind the value of the name model variable from the last step to always display the value of the HTML tag name. This updates in real-time because of Angular's data-binding technology.

4. Load the Angular Framework
Finally, we'll start our AngularJS app using:

<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
Enter fullscreen mode Exit fullscreen mode

Completed File

<html>
   <head>
      <title>AngularJS First Application</title>
   </head>

   <body>
      <h1>Sample Application</h1>

      <div ng-app = "">
         <p>Enter your Name: <input type = "text" ng-model = "name"></p>
         <p>Hello <span ng-bind = "name"></span>!</p>
      </div>

      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>

   </body>
</html>
Enter fullscreen mode Exit fullscreen mode

If you open testAngularJS.html in your browser, you'll see a page like this:

Alt Text

What to learn next

Congratulations on completing your first step towards mastering AngularJS. Now that you know how to make a basic application, you’re ready to move onto more advanced concepts. The next steps to continue your learning are:

  • Forms
  • Routing
  • Dependency Injection
  • Using APIs and CRUD operations

To help you learn AngularJS, Educative has created A Hands-on Guide to Angular. This course takes you from beginner to advanced concepts with tons of hands-on examples and interactive demonstrations. In the final sections, you'll use your skills to build your own e-commerce app to put in your portfolio.

By the end of the course, you'll have the skills to build efficient and responsive Angular applications sure to impress any interviewer.

Happy learning!

Continue reading about front-end app development

Discussion

pic
Editor guide
Collapse
niklasmtj profile image
Niklas

I think what you talk about in this article is Angular 2.
Please be aware that AngularJS angularjs.org and the modern Angular (also called Angular 2) angular.io are two different frameworks. There happened a lot of changes between AngularJS and Angular 2+. Especially in terms of syntax.

When using npm install -g @angular/cli you will install the Angular 2+ version of the CLI.

Don't feel offended, but the difference can save some headaches in finding information about Angular 😄

Collapse
pinich profile image
Pini Cheyni

I was thinking who in 2021 will still choose to post an article about AngularJS (I know there are legacy projects).
Anyway, it's AngularCLI.