Sunday, 11 November 2018

Angular Framework 20

1. Angular Framework

Angular is a TypeScript-based open-source front-end framework maintained by Google. It helps developers build scalable single-page applications (SPAs) with two-way data binding, dependency injection, routing, and modular architecture. Angular follows MVC-like patterns and provides reusable components and services.


2. Angular Modules

Definition:
Modules are containers that group related components, directives, services, and pipes. Every Angular app has a root module (AppModule) and can have multiple feature modules for modularity. They improve maintainability and lazy loading.

Example (app.module.ts):

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

3. Components

Definition:
Components are building blocks of Angular apps. They control a part of the UI using HTML templates, CSS styles, and TypeScript logic. Each component is associated with a selector used in HTML.

Example (course-card.component.ts):

import { Component } from '@angular/core'; @Component({ selector: 'app-course-card', templateUrl: './course-card.component.html', styleUrls: ['./course-card.component.css'] }) export class CourseCardComponent { title = "Angular Basics"; }

4. Services

Definition:
Services hold business logic and data retrieval logic. They are reusable across components and injected via Angular’s Dependency Injection (DI) system.

Example (courses.service.ts):

import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CoursesService { getCourses() { return ['Angular', 'React', 'Vue']; } }

5. Templates

Definition:
Templates define the view (UI) of a component using HTML and Angular syntax like interpolation ({{ }}), property binding, event binding, and structural directives.

Example (course-card.component.html):

<h2>{{ title }}</h2> <button (click)="enroll()">Enroll</button>

6. Pipes

Definition:
Pipes transform data before displaying it in templates. Angular provides built-in pipes like date, currency, uppercase, and we can create custom pipes.

Example:

<p>{{ today | date:'fullDate' }}</p>

Custom Pipe (truncate.pipe.ts):

import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'truncate' }) export class TruncatePipe implements PipeTransform { transform(value: string, limit = 10): string { return value.length > limit ? value.substring(0, limit) + '...' : value; } }

7. Routing

Definition:
Routing allows navigation between different views (components) without reloading the page. It defines paths mapped to components.

Example (app-routing.module.ts):

import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { CourseCardComponent } from './course-card/course-card.component'; const routes: Routes = [ { path: 'courses', component: CourseCardComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {}

8. Directives

Definition:
Directives are instructions in the DOM that add behavior to elements.

  • Structural Directives: Change DOM structure (*ngIf, *ngFor).

  • Attribute Directives: Change DOM appearance/behavior (ngStyle, ngClass).

  • Custom Directives: Developer-defined logic.

Example – Built-in:

<p *ngIf="isVisible">Visible Content</p> <li *ngFor="let course of courses">{{ course }}</li>
Structural Directives (change DOM layout)
  1. *ngIf – Conditionally include/exclude elements.

  2. *ngFor – Loop over arrays.

  3. *ngSwitch, *ngSwitchCase, *ngSwitchDefault – Switch-case rendering.

<div *ngIf="isLoggedIn">Welcome!</div> <ul> <li *ngFor="let course of courses">{{ course }}</li> </ul> <div [ngSwitch]="role"> <p *ngSwitchCase="'admin'">Admin Panel</p> <p *ngSwitchDefault>User Panel</p> </div>

Attribute Directives (modify appearance/behavior)

  1. ngClass – Apply classes dynamically.

  2. ngStyle – Apply styles dynamically.

  3. [(ngModel)] – Two-way data binding.

<p [ngClass]="{active: isActive}">Dynamic Class</p> <p [ngStyle]="{'color': isActive ? 'green' : 'red'}">Dynamic Style</p> <input [(ngModel)]="username">

Custom Directive Example

@Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef, private renderer: Renderer2) {} @HostListener('mouseenter') onEnter() { this.renderer.setStyle(this.el.nativeElement, 'backgroundColor', 'lightblue'); } @HostListener('mouseleave') onLeave() { this.renderer.removeStyle(this.el.nativeElement, 'backgroundColor'); } }

9. Decorators in Angular

Definition:
Decorators add metadata to classes, properties, and methods. They tell Angular how to process a class or element.

1. @NgModule

  • Defines a module that bundles components, directives, pipes, and services.

  • Every Angular app has a root module (AppModule).

  • Helps organize the application into functional blocks.

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], // components, directives, pipes imports: [BrowserModule], // other modules providers: [], // services bootstrap: [AppComponent] // root component }) export class AppModule {}

2. @Component

  • Declares a component (UI + logic).

  • Connects HTML template, CSS styles, and TypeScript logic.

import { Component } from '@angular/core'; @Component({ selector: 'app-hello', template: `<h1>Hello {{name}}</h1>`, styles: ['h1 { color: blue; }'] }) export class HelloComponent { name = 'Angular'; }

3. @Injectable

  • Declares a service available for Dependency Injection.

  • Ensures the class can be injected into components or other services.

import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' // singleton service }) export class CourseService { getCourses() { return ['Angular', 'Spring Boot', 'AWS']; } }

4. @Directive

  • Creates a custom directive (structural or attribute).

import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[appRedText]' }) export class RedTextDirective { constructor(el: ElementRef) { el.nativeElement.style.color = 'red'; } }

5. @Pipe

  • Defines a custom pipe to transform data.

import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'capitalize' }) export class CapitalizePipe implements PipeTransform { transform(value: string): string { return value.charAt(0).toUpperCase() + value.slice(1); } }

6. @Input / @Output

  • @Input → Pass data from parent to child component.

  • @Output → Send events from child to parent.

// child.component.ts @Input() title!: string; @Output() clicked = new EventEmitter<string>(); onClick() { this.clicked.emit(this.title); }

7. @HostListener / @HostBinding

  • @HostListener → Listen to DOM events.

  • @HostBinding → Bind properties to host element.

@Directive({ selector: '[appHover]' }) export class HoverDirective { @HostBinding('style.backgroundColor') bgColor = 'transparent'; @HostListener('mouseenter') onMouseEnter() { this.bgColor = 'yellow'; } @HostListener('mouseleave') onMouseLeave() { this.bgColor = 'transparent'; } }

8. @ViewChild / @ViewChildren

  • Access template DOM elements or child components.

@ViewChild('myInput') inputRef!: ElementRef; ngAfterViewInit() { console.log(this.inputRef.nativeElement.value); }

9. @ContentChild / @ContentChildren

  • Access projected content inside <ng-content>.

@ContentChild('projected') projected!: ElementRef;

10. Dependency Injection Decorators

  • @Optional → Service may or may not exist.

  • @Self → Look only in current injector.

  • @SkipSelf → Look in parent injector.

  • @Host → Look in host component injector.

Common Angular Decorators:

  • @Component → Defines a component.

  • @NgModule → Defines a module.

  • @Injectable → Marks a service for DI.

  • @Directive → Defines a custom directive.

  • @Pipe → Defines a custom pipe.

  • @Input → Pass data from parent → child.

  • @Output → Emit events child → parent.

  • @HostListener → Listen to DOM events.

  • @ViewChild / @ViewChildren → Access child elements/components.

Example (Input/Output):

@Component({ selector: 'app-child', template: `<button (click)="notify()">Notify Parent</button>` }) export class ChildComponent { @Output() notifyEvent = new EventEmitter<string>(); notify() { this.notifyEvent.emit("Hello Parent!"); } }

10. Project Architecture (src/app folder)

src/ └── app/ ├── app.module.ts ├── app.component.ts / .html / .css ├── course-card/ │ ├── course-card.component.ts / .html / .css ├── services/ │ └── courses.service.ts ├── directives/ │ └── highlighted.directive.ts ├── pipes/ │ └── truncate.pipe.ts ├── models/ │ └── course.ts └── app-routing.module.ts

11. Angular Architecture Flow (Diagram – textual form)

Modules → Components → Templates ↘ Services → Models Templates → Directives & Pipes → DOM

12. MVC Mapping in Angular

  • Model: Data models (Course class), services (CourseService).

  • View: Templates (.html), directives, and pipes controlling UI.

  • Controller: Components (.ts) act as controllers connecting Model & View.

MVC Diagram (textual form):

Model (Services + Data) ↔ Component (Controller) ↔ View (Templates + Directives + Pipes)

Some Angular CLI Commands

# Install Angular CLI npm install -g @angular/cli # Create new Angular project ng new angular-course

# To start application npm start (or) ng serve # Generate a component ng generate component course-card # Generate Angular control flow (structural directive block) ng generate @angular/core:control-flow # Generate custom directives ng g directive directives/highlighted ng g directive directives/ngx-unless # Generate a service ng g service services/courses # Generate standalone component ng generate @angular/core:standalone

2 comments: