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:

  1. Component Setup: The AppComponent is created with properties (title, count) and methods (increase, decrease) in app.component.ts.

  2. Interpolation: {{ title }} and {{ count }} bind component properties to the view dynamically.

  3. Event Binding: The (click) event triggers increase() and decrease() to modify the count value.

  4. Conditional Logic: The decrease function ensures the count does not go below zero.

  5. 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:

  1. Service Creation: QuoteService is marked with @Injectable() to be used as a singleton service.

  2. Dependency Injection: QuoteService is injected into AppComponent through the constructor.

  3. Random Selection Logic: getQuote() method returns a random string from an array of quotes.

  4. Component Interaction: The button click calls generateNewQuote(), updating the displayed quote.

  5. 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:

  1. FormsModule Usage: Enables two-way data binding with [(ngModel)] for input fields.

  2. Form Submission Handling: The login() function validates input and displays a success or error message.

  3. Conditional Rendering: *ngIf="loginError" dynamically shows an error message upon incorrect login.

  4. Encapsulation: Logic is contained in app.component.ts for modularity.

  5. 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:

  1. Routing Configuration: Defines routes for /home and /about using RouterModule.

  2. Lazy Navigation: The router-outlet dynamically loads components based on the URL.

  3. Modular Components: HomeComponent and AboutComponent manage their respective views.

  4. Navigation Links: routerLink allows users to switch between pages.

  5. Redirect Handling: Unmatched routes default to /home via redirectTo.


Each of these Angular examples introduces key framework features such as components, services, forms, and routing, providing essential skills for modern web applications.