Basic Concepts of Angular

What is Angular?

Taken from the Angular docs, "Angular is a framework and platform for building single-page apps". It is one of the big three frontend frameworks along with React and Vue. Angular consists of a few core concepts: Modules, Components, and Services. Each of these core concepts has a few concepts of its own. Modules have root modules and feature modules. Components have root components, templates, views, data binding, directives, and pipes. Services have providers and use dependency injection. This may seem like a lot because it is. Angular has a reputation for being a robust front-end framework but if you can understand Angular modules, components, and services then you are well on your way to mastering Angular.

angular lifecycle

Angular Lifecycle from Angular Documentation

Modules

Angular has some prebuilt modules to help developers, Angular calls these NgModules. NgModules are always marked with the @NgModule annotation in Angular. Some common modules are the FormsModule, RouterModule, HttpClientModule, and the Angular material design module. The idea of modules comes from the single responsibility principle. While a module can do many things, at a higher level its focus is on one thing such as forms or routing. This prevents application bloat and orders the application into concise blocks of functionality. Organizing code into modules also allows lazy loading, meaning the modules load as needed rather than all at once on application initialization. Lazy loading can help improve the load times and speed of your application, a crucial metric.

Root Module

Every Angular app will have a root module, named the AppModule, that lives in an app.module.ts file by default. This root module allows the application to bootstrap, or initialize and load, itself. Below is an example of a default AppModule.

/* JavaScript imports */
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

/* the AppModule class with the @NgModule decorator */
@NgModule({
  declarations: [AppComponent],
  imports: [],
  exports: [],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Module Metadata

An Angular module has five properties that make up its metadata, These properties are:

  1. Declarations: We can list any directives, components, or pipes here that will need to communicate with each other.
  2. Imports: Pulls in any modules like the forms or router modules.
  3. Exports: Makes components, pipes, and directives usable in other modules that import this one.
  4. Providers: Services added here become known globally to allow for dependency injection.
  5. Bootstrap: Only the root module has this property. This will contain the main application view, also called the root component.

Components

An Angular component is a Typescript class that interacts with a view. A view consists of a component and a template. A template is HTML combined with the data-binding syntax of Angular. A component has fields and methods that support a view. The view then gets updated using these properties and methods. Angular creates and destroys all components as a user moves through the application. Below is an example component taken from the Angular Tour of Heros demo app.

// Metadata
@Component({
  selector:    'app-hero-list',
  templateUrl: './hero-list.component.html',
  providers:  [ HeroService ]
})

// Actual component class
export class HeroListComponent implements OnInit {
  heroes: Hero[];
  selectedHero: Hero;

  constructor(private service: HeroService) { }

  ngOnInit() {
    this.heroes = this.service.getHeroes();
  }

  selectHero(hero: Hero) { this.selectedHero = hero; }
}

Component Metadata

An Angular component is a Typescript class at its purest but, there is one rule, it must have a @Component decorator. The @Component tag's main responsibility is connecting the template to a component, without this metadata Angular would have no idea what to do with your component. There are three important fields within the metadata tag:

  1. selector: this is what your component will be in HTML. Anywhere Angular finds this tag it will insert your component. In the example above our component would be <app-hero-list></app-hero-list>
  2. templateUrl: This is the view that corresponds to your template. You can use relative pathing here, as shown above, or you can define the HTML inline.
  3. providers: a list of services that the class uses. In the Angular example above we use the Hero service so that we can call service.getHeros()

Templates

A template is HTML that ties back to a component. A template looks like a snippet of an HTML page. In the example below, we have a template for the HeroListComponent class code from above. We can see the template uses the selectHero function that we defined in our component and also has an embedded view called <app-hero-detail>.

<h2>Hero List</h2>

<p><i>Pick a hero from the list</i></p>
<ul>
  <li *ngFor="let hero of heroes" (click)="selectHero(hero)">
    {{hero.name}}
  </li>
</ul>

<app-hero-detail *ngIf="selectedHero" [hero]="selectedHero"></app-hero-detail>

You can also nest templates. The image below shows how a template can contain other templates, child A and child B, which can then contain more templates, the grandchild template. This has the benefit of allowing segmentation of views yet show and hide entire sections of a webpage as one grouping. In the image below we would call the root template and component the host view with the child views called embedded views.

Hierarchy of Templates in Angular

Hierarchy of Templates in Angular

Data Binding

Data binding is a great quality of life improvement in Angular. It allows data to flow between your component and template. Without data binding, the Angular developer would have to write custom code to push data between the template and component. Data binding is not limited to communication between a parent template and component it can also pass data from a parent to a child component. Angular has four types of data binding, in my experience, the mustache syntax is the most used but it also depends on developer preference. The four Angular data binding forms are:

  1. interpolation: displayed as {{value}} in the image below inserts data from the component into the template.
  2. property binding: Similar to interpolation but deeper. Grabs the property in the array from the template HTML and sets the value.
  3. event binding: Allows events in the HTML/document object model to trigger functions from the component.
  4. two way binding: Allows property and event binding in one statement.

four forms of data binding in Angular

Four forms of data binding in Angular

Services

Is a general term for any bit of code that serves a specific purpose for an application. This is a broad definition but there are a few guidelines a service should follow. An Angular service should be reusable and it should follow the single responsibility principle of doing one thing and doing that one thing well. While a component handles the view a service handles everything not related to the view. Things like repeatable business logic, fetching data, or validating input that may be essential to the app but doesn't have anything to do with the visuals belong in a service. By defining this logic in a service you make it available for injection anywhere in your application, giving you infinite reusability. Angular doesn't enforce any of this when coding a service. It's not uncommon to see services that are over complicated but a well-written service will follow the principles laid out above.

Conclusion

The diagram below should make more sense now. This article has covered the basics of Angular shown in the diagram. At the core of an Angular web app is a component class paired with an HTML template. Metadata and annotations link the component and template together. They update each other through data binding, the component gets updated through event binding and the template gets updated by property binding or interpolation. Services get injected into a component through dependency injection. In future articles, I will cover pipes, directives, and more advanced Angular concepts.

angular lifecycle

Angular Lifecycle

Thanks for reading! I've included my sources below. If you want more articles like this check out my sections on Angular, AWS, TypeScript, or Java. My Medium blog also has articles not feature on this website if you want even more content.

Sources: