Build dynamic single-page applications using Angular’s
component-driven architecture, services, routing, and forms.
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.
Angular CLI is a command-line tool to scaffold and manage Angular applications.
npm install -g @angular/cli
This command creates a new Angular project with all default files.
ng new my-app
cd my-app
ng serve
An Angular project has a modular structure including:
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.
Defines the component’s metadata.
@Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.css']
})
export class HelloComponent {}
Angular supports multiple types of data binding:
{{ name }}
[src]="imagePath"
(click)="sayHello()"
[(ngModel)]="username"
Use interpolation to display data from component.ts to template.html.
<h2>Hello {{ username }}</h2>
Capture user actions such as clicks.
<button (click)="greetUser()">Click Me</button>
greetUser() { alert("Welcome!"); }
Bind input to a component property using FormsModule
.
import { FormsModule } from '@angular/forms'; // in app.module.ts
<input [(ngModel)]="username">
<p>Typed: {{ username }}</p>
Used to change the DOM layout by adding or removing elements.
*ngIf
– conditionally renders elements*ngFor
– renders list of items
<div *ngIf="isVisible">Visible Content</div>
<li *ngFor="let item of items">{{ item }}</li>
Change the appearance or behavior of an element.
[ngClass]
– bind classes dynamically[ngStyle]
– apply inline styles
<div [ngClass]="{highlight: isHighlighted}">Highlight
Me</div>
<div [ngStyle]="{color: 'blue'}">Styled Text</div>
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); }
}
Angular injects services into components automatically via the constructor.
constructor(private logger: LoggerService) {}
ngOnInit() { this.logger.log("App started"); }
Hooks are special methods that Angular calls during component initialization or destruction.
ngOnInit()
: After component is initializedngOnDestroy()
: Before component is destroyed
ngOnInit() { console.log('Component Loaded'); }
ngOnDestroy() { console.log('Component Destroyed'); }
Angular Router enables navigation between components/pages.
// app-routing.module.ts
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
RouterModule.forRoot(routes)
RouterLink creates navigation links, and RouterOutlet renders the routed component.
<a routerLink="/about">About</a>
<router-outlet></router-outlet>
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>
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) {}
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>
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 {}
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);
}
Angular uses RxJS Observables for async operations. Observables support stream-based reactive programming.
this.http.get('api/data')
.subscribe(response => console.log(response));
Automatically subscribes to an Observable in the template and displays the result.
<div *ngIf="user$ | async as user">
Welcome, {{ user.name }}
</div>
Angular includes several pipes to transform values in templates:
{{ today | date }}
{{ price | currency }}
{{ name | uppercase }}
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);
}
}
Used to protect routes and control access using services.
canActivate(): boolean {
return this.authService.isLoggedIn();
}
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) }
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);
}
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 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 {}
Used to organize code into cohesive blocks for scalability.
ng generate module products
A module containing common components, directives, and pipes used across multiple modules.
@NgModule({
declarations: [CardComponent],
exports: [CardComponent]
})
export class SharedModule {}
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';
}
}
Load components at runtime using ViewContainerRef and ComponentFactoryResolver.
this.vcr.createComponent(MyDynamicComponent);
Used to access DOM elements and component instances in the template.
<input #usernameInput>
<button (click)="log(usernameInput.value)">Log</button>
Gives access to child component or DOM element from the class.
@ViewChild('usernameInput') inputRef: ElementRef;
ngAfterViewInit() { console.log(this.inputRef.nativeElement.value);
}
Improves performance by identifying which items changed.
<li *ngFor="let item of items; trackBy: trackById">{{
item.name }}</li>
trackById(index, item) { return item.id; }
Angular checks the view model for changes using zone.js. Strategies:
Default
– runs on every changeOnPush
– runs only when inputs changeBuild the app for production and deploy using Firebase, Netlify, or any static host.
ng build --prod
firebase deploy
or
netlify deploy
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.
Angular Universal renders Angular applications on the server, improving performance and SEO.
Command: ng add @nguniversal/express-engine
Built-in animation support using @angular/animations
.
animations: [
trigger('fadeIn', [
transition(':enter', [
style({ opacity: 0 }),
animate('500ms', style({
opacity: 1 }))
])
])
]
Custom code generators using CLI. Helpful for scaffolding new components or modules with preset logic and structure.
Use fileReplacements
in angular.json
to load
different configuration files based on environment (dev/prod).
UI component library by Google with pre-built styles, layout, and responsiveness.
Install: ng add @angular/material
Use CSS Flexbox/Grid, Angular Material’s layout system, or external libraries like Bootstrap to build responsive apps.
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();
});
});
ng new app-name
– create projectng serve
– run development serverng generate component xyz
– create componentng build
– build production codeComplete guide on Angular fundamentals, advanced concepts, CLI, RxJS, and more.
Official reference for Angular CLI commands and usage patterns.
Source code, issues, and updates for the Angular framework.
https://github.com/angular/angular
Angular uses RxJS for reactive programming with observables.
https://rxjs.dev/guide/overview
Google’s official component library for Angular (Material Design-based).
Angular version of Bootstrap components.
https://valor-software.com/ngx-bootstrap/
Server-side rendering documentation for Angular Universal apps.
https://angular.io/guide/universal
A beginner-friendly YouTube tutorial to build Angular projects step by step.
https://www.youtube.com/watch?v=3qBXWUpoPHo
Simple learning modules and code snippets for Angular basics.
https://www.w3schools.com/angular/
Online code editor to run Angular projects without installing anything.