webbuild infotech

Angular Concept

All Major Concepts of Angular in Details with Example

Concepts Of Angular

Angular is a platform and framework for building single-page client applications using HTML and Typescript. Angular is written in TypeScript.

  1. Introduction
  2. The difference between AngularJS & Angular
  3. Installation & Configuration
  4. Component
  5. Modules
  6. Services
  7. Two-way data binding
  8. Pipe
  9. Routing
  10. Directive
  11. Decorator
  12. Observable
  13. Resolver
  14. Forms
1. Introduction

Angular is a platform and framework for building single-page client applications using HTML and Typescript. Angular is written in Typescript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
  constructor() { }

  ngOnInit() { }
}
2. Difference between AngularJS & Angular

The following are the major differences between AngularJS and Angular.

Sr. No.KeyAngularJSAngular
1ArchitectureAngularJS works on MVC, and Model View Controller Design. Here View shows the information present in the model and the controller processes the information.Angular uses components and directives. Here component is directive with a template.
2LanguageAngularJS code is written in javascript.Angular code is written in typescript.
3MobileAngularJS code is not mobile-friendly.Angular-developed applications are mobile browser friendly.
4Expression syntax{{}} are used to bind data between the view and the model. Special methods, ng-bind can also be used to do the same.() and [] attributes are used to bind data between the view and the model.
5Dependency InjectionDI is not used.A hierarchical DI system is used in Angular.
6Routing@routeProvider.when, they are used to provide routing information.@Route configuration is used to define routing information.
3. Installation & Configuration

Install Angular with npm as per the below command

npm install -g @angular/cli

Afterward, you can create the angular project with any name by using the ‘ng new’ command.

ng new my-app

Follow this link for more information about installation Click

4. Component

A component is a class that controls a specific part of the screen, called the view. It could be something large and always visible, like a navigation bar, or something tiny and feature specific like a single custom-made control. Components are the most basic UI building block of an Angular app. An Angular app contains a tree of Angular components. Angular components are a subset of directives, always associated with a template. Unlike other directives, only one component can be instantiated per element in a template

import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent {
   title = 'frontend';
}
5. Module

In Angular, a module is a mechanism to group components, directives, pipes, and services that are related, in such a way that can be combined with other modules to create an application.

Every Angular app has a root module, conventionally named AppModule, which provides the bootstrap mechanism that launches the application. An app typically contains many functional modules.

Like JavaScript modules, NgModules can import functionality from other Ng Modules, and allow their own functionality to be exported and used by other Ng Modules. For example, to use the router service in your app, you import the Router NgModule.

import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
// search module
import { Ng2SearchPipeModule } from 'ng2-search-filter';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ListComponent } from './users/list/list.component';
import { ManageComponent } from './users/manage/manage.component';

import { ToastrModule } from 'ngx-toastr';


@NgModule({
declarations: [
AppComponent,
ListComponent,
ManageComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule,
ReactiveFormsModule,
Ng2SearchPipeModule,
BrowserAnimationsModule,
ToastrModule.forRoot(),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
6. Services

The main objective of a service is to organize and share business logic, models, or data and functions with different components of an Angular application. It’s used to get data from the database with API.

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from "@angular/common/http";
import {environment} from '../environments/environment';
import { throwError, Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';

import { User } from '../app/models/users';

@Injectable({
   providedIn: 'root'
})
export class UserService {
  private apiServer = environment.API_URL ;
    httpOptions = {
       headers: new HttpHeaders({
       'Content-Type': 'application/json'
    })
  }
 constructor(private httpClient: HttpClient) { }
 create(User): Observable<User> {
  return this.httpClient.post<User>(this.apiServer + '/users/create', 
    JSON.stringify(User), this.httpOptions)
    .pipe(catchError(this.errorHandler))
 }

 getAll(): Observable<User[]> {
   return this.httpClient.get<User[]>(this.apiServer + '/users').pipe(
   catchError(this.errorHandler))
 }
}
7. Two-way data binding

Two-way data binding in Angular will help users to exchange data from the component to the view and from the view to the component. It will help users to establish communication bi-directionally.

Two-way data binding can be achieved using a ngModel directive in Angular. The below syntax shows the data binding using (ngModel), which is basically the combination of both the square brackets of property binding and parentheses of the event binding.

<strong>Component</strong>
import { Component} from '@angular/core';

@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent {
<strong>searchText;</strong>

constructor() { }
}

<strong>View
</strong>
<div>
   <div class="col-sm">
      <input type="text" class="form-control" 
        placeholder="Search.." <strong>[(ngModel)]="searchText"</strong> autocomplete="off"/>
   </div>
    {{<strong>searchText</strong>}}
</div>
8. Pipe

A pipe takes in a value or values and then returns a value. This is great for simple transformations on data but it can also be used in other unique ways.

import { PipeTransform, Pipe } from '@angular/core';
@Pipe({
&nbsp; &nbsp; name: 'filter'
})
export class FilterPipe implements PipeTransform {
&nbsp; &nbsp; &nbsp;transform(items: any, term: any, prop: string): any {
  &nbsp; &nbsp;   if (!term || !prop) return items;
  &nbsp; &nbsp;   return items.filter((item) => 
        item[prop].toString().toLowerCase().includes(term.toLowerCase()));
     }
}
<tr *ngFor="let user of users| filter : searchText:'email' ; let i = index ">
&nbsp; &nbsp;<td [ngClass]="user.role">{{i+ 1}}</td>
&nbsp; &nbsp;<td [ngClass]="user.role">{{user.email}}</td>
</tr>
9. Routing

Angular Router is a powerful JavaScript router built and maintained by the Angular core team that can be installed from the @angular/router package.  It enables developers to build Single Page Applications with multiple views and allows navigation between views.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ListComponent } from './users/list/list.component';
import { ManageComponent } from './users/manage/manage.component';

const routes: Routes = [
{ path: '' ,component: ListComponent},
{ path: 'create', component: ManageComponent },
{ path: 'update/:Id', component: ManageComponent } 
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
10. Directive

A directive is a function that executes whenever the Angular compiler finds in the DOM, And  Angular directives are used to extend the power of the HTML by giving it a new syntax. Each directive has a name — either one from the Angular predefined like *ngFor,*ngIf, or a custom one that can be called anything. And each directive determines where it can be used: in an elementattributeclass or comment.

11. Decorator

Decorators are design pattern that is used to separate modification or decoration of a class without modifying the original source code.

  • Class decorators, e.g. @Component and @NgModule
  • Property decorators for properties inside classes, e.g. @Input and @Output
  • Method decorators for methods inside classes, e.g. @HostListener
  • Parameter decorators for parameters inside class constructors, e.g. @Inject
12. Observable

This is just that — things you wish to observe and take action on. Observable provides support for passing messages between publishers and subscribers in your application

import { Observable } from 'rxjs/Observable';
13. Resolver

If the component renders before getting the API response, then you might be facing the issue. so resolver will be the solution and a Resolver is a class that implements the Resolve interface of Angular Router. In fact, Resolver is a service that acts like middleware, which can be executed before a component is loaded.

import&nbsp;{&nbsp;Injectable&nbsp;}&nbsp;from&nbsp;'@angular/core';

import&nbsp;{&nbsp;Resolve,&nbsp;ActivatedRouteSnapshot,&nbsp;RouterStateSnapshot&nbsp;}&nbsp;from&nbsp;'@angular/router';

import&nbsp;{&nbsp;Observable&nbsp;}&nbsp;from&nbsp;'rxjs/Observable';

import&nbsp;{&nbsp;HttpClient&nbsp;}&nbsp;from&nbsp;'@angular/common/http';

@Injectable()

export&nbsp;class&nbsp;UserResolverService&nbsp;implements&nbsp;Resolve<any>&nbsp;{

&nbsp;&nbsp;constructor(private&nbsp;http:&nbsp;HttpClient)&nbsp;{&nbsp;}

&nbsp;&nbsp;/**

&nbsp;&nbsp;&nbsp;*&nbsp;resolve&nbsp;method

&nbsp;&nbsp;&nbsp;*&nbsp;@param&nbsp;route

&nbsp;&nbsp;&nbsp;*&nbsp;@param&nbsp;state

&nbsp;&nbsp;&nbsp;*/

&nbsp;&nbsp;resolve(route:&nbsp;ActivatedRouteSnapshot):&nbsp;Observable<any>&nbsp;{

&nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;userId&nbsp;=&nbsp;route.params['id'];

&nbsp;&nbsp;&nbsp;&nbsp;const&nbsp;url&nbsp;=&nbsp;`https://jsonplaceholder.typicode.com/users/${userId}`;

&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;this.http.get(url);

&nbsp;&nbsp;}

}
14. Forms

Angular forms are used to handle the user’s input. We can use the Angular form in our application to enable users to log in, update profiles, enter information, and perform many other data-entry tasks.

there are 2 approaches to handling user input through forms:

  • Reactive forms
  • Template-driven forms

Leave a Comment

Your email address will not be published. Required fields are marked *