Lesson 1. Angular by exmple
Example 1: Basic Angular Component & Data Binding
A simple counter application demonstrating component structure, interpolation, event binding, and two-way data binding.
Code:
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular Counter';
count = 0;
increase() {
this.count++;
}
decrease() {
if (this.count > 0) {
this.count--;
}
}
}
<!-- app.component.html -->
<div class="container">
<h1>{{ title }}</h1>
<p>Current Count: {{ count }}</p>
<button (click)="increase()">Increase</button>
<button (click)="decrease()">Decrease</button>
</div>
/* app.component.css */
.container {
text-align: center;
margin-top: 50px;
}
button {
font-size: 20px;
margin: 5px;
padding: 10px;
}
Explanation:
Component Setup: The
AppComponent
is created with properties (title
,count
) and methods (increase
,decrease
) inapp.component.ts
.Interpolation:
{{ title }}
and{{ count }}
bind component properties to the view dynamically.Event Binding: The
(click)
event triggersincrease()
anddecrease()
to modify the count value.Conditional Logic: The decrease function ensures the count does not go below zero.
Styling & Layout: The UI is styled using CSS in
app.component.css
to align and style buttons.
Example 2: Angular Services & Dependency Injection
This example creates a service to fetch random quotes.
Code:
// quote.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class QuoteService {
private quotes: string[] = [
"Stay hungry, stay foolish.",
"Code is like humor. When you have to explain it, it’s bad.",
"Simplicity is the soul of efficiency."
];
getQuote(): string {
return this.quotes[Math.floor(Math.random() * this.quotes.length)];
}
}
// app.component.ts
import { Component } from '@angular/core';
import { QuoteService } from './quote.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
quote: string;
constructor(private quoteService: QuoteService) {
this.quote = this.quoteService.getQuote();
}
generateNewQuote() {
this.quote = this.quoteService.getQuote();
}
}
<!-- app.component.html -->
<div class="quote-container">
<h2>Random Quote</h2>
<p>{{ quote }}</p>
<button (click)="generateNewQuote()">New Quote</button>
</div>
Explanation:
Service Creation:
QuoteService
is marked with@Injectable()
to be used as a singleton service.Dependency Injection:
QuoteService
is injected intoAppComponent
through the constructor.Random Selection Logic:
getQuote()
method returns a random string from an array of quotes.Component Interaction: The button click calls
generateNewQuote()
, updating the displayed quote.Encapsulation & Reusability: Services allow logic reuse across multiple components.
Example 3: Angular Forms & Validation
A login form with basic validation using Angular FormsModule.
Code:
// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
username = '';
password = '';
loginError = false;
login() {
if (this.username === 'admin' && this.password === 'password') {
alert('Login successful!');
this.loginError = false;
} else {
this.loginError = true;
}
}
}
<!-- app.component.html -->
<form (ngSubmit)="login()">
<label>Username:</label>
<input type="text" [(ngModel)]="username" required>
<label>Password:</label>
<input type="password" [(ngModel)]="password" required>
<button type="submit">Login</button>
<p *ngIf="loginError">Invalid username or password!</p>
</form>
Explanation:
FormsModule Usage: Enables two-way data binding with
[(ngModel)]
for input fields.Form Submission Handling: The
login()
function validates input and displays a success or error message.Conditional Rendering:
*ngIf="loginError"
dynamically shows an error message upon incorrect login.Encapsulation: Logic is contained in
app.component.ts
for modularity.Real-World Applicability: Demonstrates basic authentication logic for user input validation.
Example 4: Angular Routing & Navigation
A multi-page application using Angular RouterModule.
Code:
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
// home.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
template: `<h2>Home Page</h2><p>Welcome to our website!</p>`,
styles: ['h2 { color: blue; }']
})
export class HomeComponent { }
// about.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-about',
template: `<h2>About Page</h2><p>We build great software!</p>`,
styles: ['h2 { color: green; }']
})
export class AboutComponent { }
<!-- app.component.html -->
<nav>
<a routerLink="/home">Home</a> | <a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>
Explanation:
Routing Configuration: Defines routes for
/home
and/about
usingRouterModule
.Lazy Navigation: The
router-outlet
dynamically loads components based on the URL.Modular Components:
HomeComponent
andAboutComponent
manage their respective views.Navigation Links:
routerLink
allows users to switch between pages.Redirect Handling: Unmatched routes default to
/home
viaredirectTo
.
Each of these Angular examples introduces key framework features such as components, services, forms, and routing, providing essential skills for modern web applications.