Angular-Cheatsheet

👋 Hello Angular

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: '<h1>Hello Angular!</h1>',
})
export class AppComponent { }

💡 Tip: Use the Angular CLI to generate a new project — ng new my-app.

🧩 Components

// hero.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-hero',
  templateUrl: './hero.component.html',
  styleUrls: ['./hero.component.css']
})
export class HeroComponent {
  name = 'Iron Man';
}

💡 Tip: Components = template + logic + style. Create with ng generate component hero.

🔗 Data Binding

<!-- hero.component.html -->
<h2>{{ name }}</h2>  <!-- Interpolation -->
<button (click)="sayHello()">Click</button>
<input [(ngModel)]="name" />  <!-- Two-way binding -->

💡 Tip: Use [(ngModel)] for two-way binding. Import FormsModule in your module.

🧭 Directives

<!-- app.component.html -->
<p *ngIf="isVisible">Now you see me!</p>
<ul>
  <li *ngFor="let item of items">{{ item }}</li>
</ul>
<div [ngClass]="{'highlight': isActive}">Styled div</div>

💡 Tip: Built-in directives: *ngIf, *ngFor, [ngClass], [ngStyle].

⚙️ Services & Dependency Injection

// logger.service.ts
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class LoggerService {
  log(message: string) {
    console.log('Log:', message);
  }
}

// hero.component.ts
constructor(private logger: LoggerService) { }

sayHello() {
  this.logger.log(`Hello from ${this.name}`);
}

💡 Tip: Services are singletons used across components. Add @Injectable() decorator.

🧭 Routing

// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

💡 Tip: Use <router-outlet> in your template to render routed components.

🌐 HTTP Client

// data.service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class DataService {
  constructor(private http: HttpClient) { }

  getUsers() {
    return this.http.get('https://jsonplaceholder.typicode.com/users');
  }
}

💡 Tip: Import HttpClientModule once in your root module to enable HTTP calls.

🔄 Pipes

<!-- app.component.html -->
<p>{{ title | uppercase }}</p>
<p>{{ today | date:'longDate' }}</p>
<p>{{ price | currency:'USD' }}</p>

💡 Tip: Use custom pipes for reusable data transformations.

⏳ Lifecycle Hooks

import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({ selector: 'app-demo', template: '' })
export class DemoComponent implements OnInit, OnDestroy {
  ngOnInit() {
    console.log('Component Initialized');
  }
  ngOnDestroy() {
    console.log('Component Destroyed');
  }
}

💡 Tip: Common hooks: ngOnInit, ngOnChanges, ngAfterViewInit.

🧾 Reactive Forms

import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';

@Component({ selector: 'app-login', templateUrl: './login.component.html' })
export class LoginComponent {
  form = this.fb.group({
    email: ['', [Validators.required, Validators.email]],
    password: ['', Validators.required],
  });

  constructor(private fb: FormBuilder) { }

  submit() {
    console.log(this.form.value);
  }
}

💡 Tip: Import ReactiveFormsModule to use form builders and validators.

📡 Observables (RxJS)

import { of } from 'rxjs';
import { map, filter } from 'rxjs/operators';

of(1, 2, 3, 4)
  .pipe(
    filter(n => n % 2 === 0),
    map(n => n * 10)
  )
  .subscribe(val => console.log(val));

💡 Tip: Observables are at the core of Angular’s reactivity. Use async pipe in templates.

💻 Angular CLI Commands

// Create a new app
ng new my-app

// Generate a component, service, or module
ng g c user
ng g s auth
ng g m shared

// Run development server
ng serve --open

💡 Tip: Use CLI generators to maintain clean, consistent code structure.

🔒 Routing Guards

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';

@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
  canActivate() {
    return confirm('Are you logged in?');
  }
}

💡 Tip: Guards control route access (auth, roles, conditions).

Post a Comment