ANGULAR FRAMEWORK

Build dynamic single-page applications using Angular’s
component-driven architecture, services, routing, and forms.

Angular - Complete Frontend Framework by Google

1. What is Angular?

Angular is a TypeScript-based open-source front-end web framework developed by Google. It provides a complete solution for building dynamic web applications, including routing, state management, dependency injection, and component-based UI development.

2. Installing Angular CLI

Angular CLI is a command-line tool to scaffold and manage Angular applications.

npm install -g @angular/cli
3. Creating a New Angular App

This command creates a new Angular project with all default files.

ng new my-app
cd my-app
ng serve
4. Angular Project Structure

An Angular project has a modular structure including:

5. Components in Angular

Components are the building blocks of Angular UI. Created using CLI:

ng generate component hello

This creates a folder with `.ts`, `.html`, `.css`, and `.spec.ts` files.

6. Component Decorator

Defines the component’s metadata.

@Component({
  selector: 'app-hello',
  templateUrl: './hello.component.html',
  styleUrls: ['./hello.component.css']
})
export class HelloComponent {}
7. Data Binding

Angular supports multiple types of data binding:

8. Displaying Data in HTML

Use interpolation to display data from component.ts to template.html.

<h2>Hello {{ username }}</h2>
9. Event Binding Example

Capture user actions such as clicks.

<button (click)="greetUser()">Click Me</button>
greetUser() { alert("Welcome!"); }
10. Two-Way Data Binding with ngModel

Bind input to a component property using FormsModule.

import { FormsModule } from '@angular/forms'; // in app.module.ts

<input [(ngModel)]="username">
<p>Typed: {{ username }}</p>

Angular – Directives, Services, Dependency Injection

11. Structural Directives

Used to change the DOM layout by adding or removing elements.

<div *ngIf="isVisible">Visible Content</div>
<li *ngFor="let item of items">{{ item }}</li>
12. Attribute Directives

Change the appearance or behavior of an element.

<div [ngClass]="{highlight: isHighlighted}">Highlight Me</div>
<div [ngStyle]="{color: 'blue'}">Styled Text</div>
13. Angular Service

Services are used to share logic or data across components. Services are reusable and follow the singleton pattern.

// logger.service.ts
@Injectable({ providedIn: 'root' })
export class LoggerService {
  log(msg: string) { console.log(msg); }
}
14. Dependency Injection

Angular injects services into components automatically via the constructor.

constructor(private logger: LoggerService) {}
ngOnInit() { this.logger.log("App started"); }
15. Lifecycle Hooks

Hooks are special methods that Angular calls during component initialization or destruction.

ngOnInit() { console.log('Component Loaded'); }
ngOnDestroy() { console.log('Component Destroyed'); }
16. Routing and Navigation

Angular Router enables navigation between components/pages.

// app-routing.module.ts
const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent }
];
RouterModule.forRoot(routes)
17. RouterLink and RouterOutlet

RouterLink creates navigation links, and RouterOutlet renders the routed component.

<a routerLink="/about">About</a>
<router-outlet></router-outlet>
18. Forms in Angular

Angular supports Template-driven and Reactive Forms. Template-driven forms are simpler for basic use cases.

<form #myForm="ngForm">
  <input name="email" ngModel required />
  <button>Submit</button>
</form>
19. Reactive Forms

More scalable, testable, and reactive way to manage forms using FormBuilder and FormGroup.

form = this.fb.group({
  email: ['', [Validators.required, Validators.email]]
});

constructor(private fb: FormBuilder) {}
20. Form Validation

Built-in validators and custom validators help in input validation.

<input name="email" ngModel required email />
<div *ngIf="myForm.controls.email.errors">Invalid email!</div>

Angular – HTTP, Pipes, Guards, and Advanced Features

21. HTTPClient Module

Used to make HTTP requests (GET, POST, PUT, DELETE) to backend services.

// In app.module.ts
import { HttpClientModule } from '@angular/common/http';
@NgModule({ imports: [HttpClientModule] })
export class AppModule {}
22. Making GET Request

Use HttpClient to fetch data from an API.

constructor(private http: HttpClient) {}
ngOnInit() {
  this.http.get('https://jsonplaceholder.typicode.com/posts')
    .subscribe(data => this.posts = data);
}
23. Observables

Angular uses RxJS Observables for async operations. Observables support stream-based reactive programming.

this.http.get('api/data')
  .subscribe(response => console.log(response));
24. Async Pipe

Automatically subscribes to an Observable in the template and displays the result.

<div *ngIf="user$ | async as user">
  Welcome, {{ user.name }}
</div>
25. Built-in Pipes

Angular includes several pipes to transform values in templates:

26. Custom Pipes

You can create your own pipe for custom formatting logic.

@Pipe({ name: 'capitalize' })
export class CapitalizePipe implements PipeTransform {
  transform(value: string) {
    return value.charAt(0).toUpperCase() + value.slice(1);
  }
}
27. Route Guards

Used to protect routes and control access using services.

canActivate(): boolean {
  return this.authService.isLoggedIn();
}
28. Lazy Loading Modules

Helps improve app performance by loading feature modules only when needed.

// app-routing.module.ts
{ path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }
29. Interceptors

Used to modify HTTP requests/responses globally (e.g., add auth token).

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  const authReq = req.clone({ headers: req.headers.set('Authorization', 'Bearer xyz') });
  return next.handle(authReq);
}
30. Environment Configuration

Use environment.ts and environment.prod.ts for different API URLs or settings per build type.

// environment.ts
export const environment = { apiUrl: 'http://localhost:3000' };

Angular – Advanced Features and Best Practices

31. Modules in Angular

Angular uses NgModules to group components, directives, pipes, and services. Every Angular app has a root module (`AppModule`).

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent]
})
export class AppModule {}
32. Feature Modules

Used to organize code into cohesive blocks for scalability.

ng generate module products
33. Shared Module

A module containing common components, directives, and pipes used across multiple modules.

@NgModule({
  declarations: [CardComponent],
  exports: [CardComponent]
})
export class SharedModule {}
34. Custom Directives

Used to create your own behavior or styles in HTML templates.

@Directive({ selector: '[appHighlight]' })
export class HighlightDirective {
  constructor(el: ElementRef) {
    el.nativeElement.style.backgroundColor = 'yellow';
  }
}
35. Dynamic Components

Load components at runtime using ViewContainerRef and ComponentFactoryResolver.

this.vcr.createComponent(MyDynamicComponent);
36. Template Reference Variables

Used to access DOM elements and component instances in the template.

<input #usernameInput>
<button (click)="log(usernameInput.value)">Log</button>
37. ViewChild Decorator

Gives access to child component or DOM element from the class.

@ViewChild('usernameInput') inputRef: ElementRef;
ngAfterViewInit() { console.log(this.inputRef.nativeElement.value); }
38. TrackBy in ngFor

Improves performance by identifying which items changed.

<li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>
trackById(index, item) { return item.id; }
39. Change Detection

Angular checks the view model for changes using zone.js. Strategies:

40. Deployment Using Angular CLI

Build the app for production and deploy using Firebase, Netlify, or any static host.

ng build --prod
firebase deploy
or
netlify deploy

Angular – Final Topics and Best Practices

41. Reactive State Management (NgRx)

NgRx is a Redux-inspired state management library for Angular. It uses actions, reducers, and stores for global state handling.

Best suited for large-scale applications with shared state across components.

42. Angular Universal (Server-Side Rendering)

Angular Universal renders Angular applications on the server, improving performance and SEO.

Command: ng add @nguniversal/express-engine

43. Angular Animations

Built-in animation support using @angular/animations.

animations: [
  trigger('fadeIn', [
    transition(':enter', [
      style({ opacity: 0 }),
      animate('500ms', style({ opacity: 1 }))
    ])
  ])
]
44. Angular Schematics

Custom code generators using CLI. Helpful for scaffolding new components or modules with preset logic and structure.

45. Environment-specific Configuration

Use fileReplacements in angular.json to load different configuration files based on environment (dev/prod).

46. Angular Material

UI component library by Google with pre-built styles, layout, and responsiveness.

Install: ng add @angular/material

47. Responsive Design

Use CSS Flexbox/Grid, Angular Material’s layout system, or external libraries like Bootstrap to build responsive apps.

48. Testing in Angular

Uses Jasmine and Karma for unit testing and Protractor or Cypress for end-to-end testing.

describe('ComponentName', () => {
  it('should create component', () => {
    expect(component).toBeTruthy();
  });
});
49. Angular CLI Commands (Quick Reference)
50. Angular Best Practices

Angular Reference Links

1. Official Angular Documentation

Complete guide on Angular fundamentals, advanced concepts, CLI, RxJS, and more.

https://angular.io/docs

2. Angular CLI Documentation

Official reference for Angular CLI commands and usage patterns.

https://angular.io/cli

3. Angular GitHub Repository

Source code, issues, and updates for the Angular framework.

https://github.com/angular/angular

4. RxJS (Reactive Extensions) Documentation

Angular uses RxJS for reactive programming with observables.

https://rxjs.dev/guide/overview

5. Angular Material UI

Google’s official component library for Angular (Material Design-based).

https://material.angular.io/

6. NGX Bootstrap Documentation

Angular version of Bootstrap components.

https://valor-software.com/ngx-bootstrap/

7. Angular Universal (SSR)

Server-side rendering documentation for Angular Universal apps.

https://angular.io/guide/universal

8. Angular Tutorial by FreeCodeCamp

A beginner-friendly YouTube tutorial to build Angular projects step by step.

https://www.youtube.com/watch?v=3qBXWUpoPHo

9. Angular Courses on W3Schools

Simple learning modules and code snippets for Angular basics.

https://www.w3schools.com/angular/

10. StackBlitz for Angular

Online code editor to run Angular projects without installing anything.

https://stackblitz.com/fork/angular