Angular Fundamental

This section will cover the Components, Creation of Components, Lifecycle of the Component, and various directives provided by Angular & lastly, we will discuss the Decorator.

The Component is the basic building block for developing UI for any Angular app, which contains the tree of Angular Component. The Directives are the subset for the components, where the Components are always associated with the template. Only a single Component would be instantiated for a given element in the template.

The Components should belong to the NgModule, which helps to avail the component to another component or application.

In order to do this, the component should be listed in the declarations field of the NgModule metadata. 

Creating Component:

The Angular application is composed of a different set of components, where every component has different roles & functionality that is designed to perform the specific task. The Components can be created with the following command:

ng generate component <component-name>

Please refer to the Components in Angular 8 article for further detailed descriptions.

Lifecycle Hooks of Component:

Every Component has its own lifecycle, which will be started when Angular instantiates the particular Component class that renders the Component view along with the child view. It is basically timed methods that differ when and why they execute. These methods will be triggered with the change detection, i.e., depending upon the conditions, the corresponding cycle will be executed.

Angular will constantly check when the data-bound properties changes & accordingly update both the view & the Component instances, as required. The order of the execution for these lifecycle hooks is important.

The Component instance will be destroyed & will be removed its rendered templates from the DOM by Angular when the lifecycle ends.

The different lifecycle hook methods for the Component are described below:

Methods

Descriptions

Syntax

ngOnChanges()

Triggered when the Angular set or reset the data-bound input properties

export class AppComponent implements OnChanges {
@Input() geeks: string;
lifecycleCount: number = 20;
ngOnChanges() {
  this.lifecycleCount–;
}
}

ngOnInit()

Used to initialize the Component or Directive after Angular sets the initial display of data-bound properties and sets input properties.

export class AppComponent implements OnInit {
@Input() geeks: string;
lifecycleCount: number = 20;
ngOnInit() {
   this.lifecycleCount–;
}
}

ngDoCheck()

Called immediately after changes detected by ngOnChanges() and after the initial execution of ngOnInit().

ngDoCheck() {
  console.log(++this.lifecycleCount);
  …
  }
}

ngAfterContentInit()

Used to perform initialization after Angular projects external content into the component’s view.

ngAfterContentInit() {

}

ngAfterContentChecked()

ngAfterContentChecked() is utilized to perform checks after Angular checks the content projected into the component’s view.

ngAfterContentChecked() {

}

ngAfterViewInit()

ngAfterViewInit() is employed to execute logic after Angular initializes the component’s views and child views.

ngAfterViewInit() {

}

ngAfterViewChecked()

ngAfterViewChecked() is utilized to execute logic after Angular checks the component’s views and child views for changes.

ngAfterViewChecked() {

}

ngOnDestroy()

ngOnDestroy() is used to perform cleanup logic when the component is destroyed or removed from the DOM.

export class AppComponent {
destroy: boolean = true;
DataDestroy() {
  this.destroy = !this.destroy;
}

Modules:

Every Angular application contains the root module, called NgModules, which acts as the container for the cohesive block of code, that is specifically designed to that application domain, a workflow, or a closely related set of capabilities. It consists of the components, services, & other code files, whose scope is decided by the NgModules.

The NgModules in the AppModule, reside in the app.module.ts file. The  @NgModule() class decorator is used to define the NgModule. It is a function that accepts one metadata object, whose properties describe the module.

Some of the important properties are described below:

Properties

Descriptions

declarations

The components, directives, and pipes will belong to this NgModule.

exports

It is a subset of declarations, which will be visible & usable should in the component templates of other NgModules.

imports

It depicts the other modules whose exported classes are required by the component templates declared in this NgModule

providers

It is the Creator of services, that is contributed to the global collection of services & becomes accessible in all parts of the application.

bootstrap

The root component hosts all other application views. The bootstrap property should be set by the root NgModule only.

The data can be shared between the parent component and one or more child components by implementing the @Input() and @Output() decorators, which provide the child component a way to communicate with its parent component.

The @Input() decorator helps to update the data by the parent component in the child component, while the @Output() decorator helps to send the data by the child component to the parent component.

Angular Template:

The Template is a blueprint of the Angular application for developing the enhanced user interface, written in HTML & special syntax can be used within a template. Basically, each Template represents the section of the code on an HTML page that will be rendered in the browser with a lot more functionality.

While generating the application through the Angular CLI, the app.component.html will be the default template that will contain the HTML code. The Template Syntax helps to control the UX/UI by coordinating the data between the class and the template.

Angular provides several template syntax, which is described below:

Templates

Descriptions

Syntax

Text Interpolation

It displays component properties in the view template, allowing properties from the component class to be reflected in the template.

class=”{{variable_name}}”

Template Statement

Refers to event bindings or event handling mechanisms within the template syntax, allowing you to respond to user actions like clicks, input changes, etc.

<element type=”button” (click)=”ChangeData()”>Delete</element>

Binding

Binding in Angular connects the HTML template with the model, syncing the view and model. It facilitates communication between them, focusing on the target receiving the value and the template expression producing it.

<element [(expression)]=”ClassName”></element>

Pipes

It is used to transform the strings, currency amounts, dates, and other data, without affecting the actual content. 

{{ Expression | data }}

We will learn about the various concepts of Binding & Pipes in more detail, in the underneath section.

Directives:

The Directive is generally a built-in class that includes the additional behavior to elements in the Angular Applications.

There are 2 types of directives:

  • Attribute Directive: The Attribute Directive is used to modify the appearance or change the behavior of DOM elements & the components in Angular. In this case, the element, component, or another directive can be styled. The list of most commonly used attribute directives is:

Directives

Descriptions

Syntax

ngClass

Built-in Angular directive used for dynamically adding or removing CSS classes from an HTML element based on certain conditions.

<element [ng-class]=”expression”> 
   Contents… 
</element>

ngStyle

 This directive is used to manipulate the styles for the HTML elements. It is a set of more than one style property, that is specified with colon-separated key-value pairs.

<element [ngStyle] = “typescript_property”>

ngModel

This directive is used to create a top-level form group Instance, and it binds the form to the given form value.

<Input [(NgModel)= ‘name’]>

  • Structural Directive: The Structural Directive is used to change the structure of the element or the component, i.e. it is used for modifying the structure of the DOM by applying or removing the elements from the DOM. The set of most commonly used built-in structural directives is:

Directives

Descriptions

Syntax

NgIf

This directive is used to remove or recreate a portion of an HTML element based on an expression. If the expression inside it is false then the element is removed and if it is true then the element is added to the DOM.

<element *ngIf=’condition’></element>

NgFor

This directive is used to render each element for the given collection each element can be displayed on the page.

<element *ngFor=’condition’></element>

NgSwitch

This directive is used to specify the condition to show or hide the child elements.

<element *NgSwitch=’condition’></element>

Decorators:

The Decorators are the function that is called with the prefix @ symbol, immediately followed by the class, methods, or property. The Service, filter, or directive are allowed to be modified by the Decorators before they are utilized.

It facilitates the metadata for configuration that decides how the components, function or class are to be processed, instantiated & utilized during the runtime.

All the Decorators can be categorized in 2 ways & each type of Decorator contains its own subset of the decorators, which are described below:

  • Class Decorators: This decorator is facilitated by Angular having some class, which permits us to specify whether the particular class is a component or a module, along with permitting us to define this effect without having any code inside of it. For eg., the @Component that provides the metadata as part of the class & @NgModule clicks the widely used classes.

Some other Class decorators are:

Class Decorator

Descriptions

Syntax

import

This is usually used to import the Directives from the @angular/core.

import { NgModule } from ‘@angular/core’;

@Directive

It is used to define the class as the Directive & provides its metadata of it.

@Directive({

})

@Pipe

This is used to define the class as the Pipe, along with providing its metadata of it.

@Pipe({
 …
})

@Injectable

This is used to declare the class to be injected. When this is injected somewhere, the compiler can’t generate sufficient metadata that allows for the creation of the class appropriately, without having this decorator.

@Injectable({
 …
})

  • Class Field Decorator: This is another category of Decorator, which can contain the following types:

Class Field Decorators

Descriptions

Syntax

Property decorator

This decorator can be utilized to decorate the particular properties declared inside the class. With this decorator, we can easily detect the purpose of using any particular property of the class. For eg., @Input(), @Output(), ReadOnly(), @Override() are most used property decorators.

class GFG {
 @ReadOnly(‘check’) 
 name: string = ‘DSA’;
}

Method Decorators

Method decorators like @HostListener and @HostBinding are used to decorate methods inside classes to add functionality, commonly linking host element properties with directive methods or binding host element properties with component properties.

export class AppComponent {
 @HostListener(‘click’, [‘$event’])
 onHostClick(event: Event) {
code…
 }
}

Parameter Decorator

This decorator is permitted to decorate the parameter in the class constructors. The commonly used decorator of this type is @Inject, which is used for injecting the services in the Angular Class. 

export class GFGExample{
   constructor(@Inject(gfgService) gfgServ)
   console.log(gfgServ);
 }


Example 2: This example describes the basic implementation of the Directives & the Decorators in Angular.

HTML
<!-- app.component.html File-->


<!-- ngClass & ngIf -->
<div *ngIf="true" [ngClass]="'gfgclass'"> 
This text will be displayed
<!-- ngStyle -->
<h1 [ngStyle]="{'color':'#00FF00'}">
   GFG Structural Directive Example
</h1>
</div>
<hr>
<!-- ngFor -->
<div *ngFor="let item of items">
   <p> {{item}} </p>
</div>
<hr>
<!-- ngSwitch -->
<div [ngSwitch]="'one'">
   <div *ngSwitchCase="'one'">One is Displayed</div>
   <div *ngSwitchCase="'two'">Two is Displayed</div>
   <div *ngSwitchDefault>Default Option is Displayed</div>
</div>
<hr>
<h1>
   w3wiki
</h1>
<hr>
<h2>w3wiki</h2>
<!-- ngModel -->
<input [(ngModel)]="gfg" #ctrl="ngModel" required>
<p>Value: {{ gfg }}</p>
<button (click)="setValue()">Set value</button>
JavaScript
// app.component.ts File

import { Component, VERSION } from "@angular/core";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
items = ["GfG 1", "GfG 2", "GfG 3", "GfG 4"];
gfg: string = "";
setValue() {
this.gfg = "w3wiki";
}
}
JavaScript
// app.module.ts File

import { NgModule } from "@angular/core";
import { BrowserModule } 
from "@angular/platform-browser";
import { FormsModule } from "@angular/forms";
import { AppComponent } from "./app.component";
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule {}


Angular Cheat Sheet – A Basic Guide to Angular

Angular is a client-side TypeScript-based, front-end web framework developed by the Angular Team at Google, that is mainly used to develop scalable single-page web applications(SPAs) for mobile & desktop.

Angular is a great, reusable UI (User Interface) library for developers that helps in building attractive, steady, and utilitarian web pages and web applications. It is a continuously growing and expanding framework that provides better ways for developing web applications. It changes the static HTML to dynamic HTML. Its features like dynamic binding and dependency injection eliminate the need for code that we have to write otherwise.

TypeScript is a Strict Super Set of JavaScript, which means anything that is implemented in JavaScript can be implemented using TypeScript.

Angular Cheat Sheet

Similar Reads

What is Angular Cheat Sheet?

The Angular Cheat Sheet will give quick ideas related to the topics like Basics, Lifecycle Hooks, Components & Modules, Directives, Decorators, Angular Forms, Pipes, Services, Routing & many more, which will provide you a gist of Angular with their basic implementation....

Angular Introduction

Angular is a component-based application design framework, build on Typescript, for creating a sophisticated & a scalable single-page web application that has a well-integrated collection of libraries that helps to develop the code in module-wise with an easy-to-update, debug module. In order to work with Angular, we must have node.js, Node Package Manager(NPM) & Angular CLI installed in the system....

Creating a New Angular Project

After successful installation of the node.js & npm, we need to install the Angular CLI, which is described below:...

Boilerplate

Example 1: This example illustrates the basic Angular web app....

Angular Fundamental

This section will cover the Components, Creation of Components, Lifecycle of the Component, and various directives provided by Angular & lastly, we will discuss the Decorator....

Data Bindings

Data Binding is a technique to automatically synchronize the data between the model and view components. Angular implements data-binding that treats the model as the single source of truth in your application & for all the time, the view is a projection of the model....

Angular Forms

The Angular Form is an integral part of any web application, which may contain the collection of controls for an input field, buttons, checkboxes, etc, along with having the validation check that enables to validate data entered by the user in an appropriate form....

Angular Pipes

Pipes in Angular can be used to transform the strings, currency amounts, dates, and other data, without affecting the actual content. This is a simple function that can be used with the interpolation(template expression), in order to accept the input value & return the transformed data....

Services & Dependency Injection

The Service facilitates the services to various components, in order to complete a certain task or to perform the specific operation that needs to be accomplished by the application....

Routing

The Router helps to navigate between pages that are being triggered by the user’s actions. The navigation happens when the user clicks on the link or enters the URL from the browser address bar....