logo
eng-flag

Angular Cheatsheet

Table of Contents

  1. Components
  2. Templates
  3. Directives
  4. Pipes
  5. Services
  6. Dependency Injection
  7. Routing
  8. Forms
  9. HTTP Client
  10. Observables
  11. Modules
  12. Lifecycle Hooks
  13. Change Detection
  14. Decorators
  15. Angular CLI
  16. Testing
  17. Animations
  18. Security
  19. Internationalization
  20. Optimizations

Components

Basic Component

import { Component } from '@angular/core';

@Component({
  selector: 'app-hello',
  template: '<h1>Hello, {{name}}!</h1>',
  styles: ['h1 { font-weight: normal; }']
})
export class HelloComponent {
  name: string = 'Angular';
}

Component with Input and Output

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <h2>{{childTitle}}</h2>
    <button (click)="sendMessage()">Send Message</button>
  `
})
export class ChildComponent {
  @Input() childTitle: string;
  @Output() messageEvent = new EventEmitter<string>();

  sendMessage() {
    this.messageEvent.emit('Hello from child!');
  }
}

Templates

Interpolation

<h1>{{title}}</h1>
<p>Sum: {{ 1 + 1 }}</p>
<p>String manipulation: {{ title.toUpperCase() }}</p>

Property Binding

<img [src]="imageUrl">
<button [disabled]="isUnchanged">Disabled Button</button>

Event Binding

<button (click)="onSave()">Save</button>
<input (keyup.enter)="onEnter($event)">

Two-way Binding

<input [(ngModel)]="name">

Directives

Built-in Directives

<p *ngIf="condition">Conditional content</p>

<ul>
  <li *ngFor="let item of items; let i = index">{{i}}: {{item}}</li>
</ul>

<div [ngSwitch]="conditionExpression">
  <ng-container *ngSwitchCase="expression1">Output 1</ng-container>
  <ng-container *ngSwitchCase="expression2">Output 2</ng-container>
  <ng-container *ngSwitchDefault>Default output</ng-container>
</div>

<div [ngClass]="{'active': isActive, 'disabled': isDisabled}">
  Styled content
</div>

<div [ngStyle]="{'color': textColor, 'font-size': fontSize + 'px'}">
  Styled content
</div>

Custom Attribute Directive

import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  @Input('appHighlight') highlightColor: string;

  constructor(private el: ElementRef) {}

  ngOnInit() {
    this.el.nativeElement.style.backgroundColor = this.highlightColor || 'yellow';
  }
}

Pipes

Built-in Pipes

<p>{{ dateValue | date:'short' }}</p>
<p>{{ price | currency:'USD':'symbol':'1.2-2' }}</p>
<p>{{ longText | slice:0:50 }}...</p>

Custom Pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'exponentialStrength'})
export class ExponentialStrengthPipe implements PipeTransform {
  transform(value: number, exponent = 1): number {
    return Math.pow(value, exponent);
  }
}

Services

Basic Service

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

@Injectable({
  providedIn: 'root'
})
export class DataService {
  private data: string[] = [];

  addData(item: string) {
    this.data.push(item);
  }

  getData(): string[] {
    return this.data;
  }
}

Dependency Injection

Injecting a Service

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-my-component',
  template: '<ul><li *ngFor="let item of items">{{item}}</li></ul>'
})
export class MyComponent {
  items: string[];

  constructor(private dataService: DataService) {
    this.items = this.dataService.getData();
  }
}

Routing

Basic Routes

import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: 'contact', component: ContactComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent }
];

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

Router Outlet

<router-outlet></router-outlet>
<a routerLink="/home">Home</a>
<a [routerLink]="['/user', userId]">User Profile</a>

Forms

Template-driven Form

<form (ngSubmit)="onSubmit()" #myForm="ngForm">
  <div>
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" [(ngModel)]="model.name" required>
  </div>
  <button type="submit" [disabled]="!myForm.form.valid">Submit</button>
</form>

Reactive Form

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

@Component({
  selector: 'app-profile-editor',
  templateUrl: './profile-editor.component.html'
})
export class ProfileEditorComponent {
  profileForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.profileForm = this.fb.group({
      firstName: ['', Validators.required],
      lastName: [''],
      address: this.fb.group({
        street: [''],
        city: [''],
        state: [''],
        zip: ['']
      })
    });
  }

  onSubmit() {
    console.log(this.profileForm.value);
  }
}

HTTP Client

GET Request

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

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

  getData(): Observable<any> {
    return this.http.get('https://api.example.com/data');
  }
}

POST Request

postData(data: any): Observable<any> {
  return this.http.post('https://api.example.com/data', data);
}

Observables

Basic Usage

import { Observable } from 'rxjs';

const myObservable = new Observable(observer => {
  observer.next('Hello');
  observer.next('World');
  observer.complete();
});

myObservable.subscribe(
  value => console.log(value),
  error => console.error(error),
  () => console.log('Completed')
);

Modules

Feature Module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FeatureComponent } from './feature.component';

@NgModule({
  imports: [CommonModule],
  declarations: [FeatureComponent],
  exports: [FeatureComponent]
})
export class FeatureModule { }

Lifecycle Hooks

Common Lifecycle Hooks

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

@Component({
  selector: 'app-lifecycle',
  template: '<p>Lifecycle Component</p>'
})
export class LifecycleComponent implements OnInit, OnDestroy {
  ngOnInit() {
    console.log('Component initialized');
  }

  ngOnDestroy() {
    console.log('Component destroyed');
  }
}

Change Detection

OnPush Strategy

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

@Component({
  selector: 'app-on-push',
  template: '<p>{{data}}</p>',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class OnPushComponent {
  data: string = 'Initial data';
}

Decorators

Property Decorator

import { Input, Output, EventEmitter } from '@angular/core';

export class MyComponent {
  @Input() inputProperty: string;
  @Output() outputEvent = new EventEmitter<string>();
}

Angular CLI

Common Commands

ng new my-app
ng serve
ng generate component my-component
ng build --prod
ng test
ng lint

Testing

Component Test

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ MyComponent ]
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Animations

Basic Animation

import { trigger, state, style, animate, transition } from '@angular/animations';

@Component({
  selector: 'app-animate',
  template: '<div [@openClose]="isOpen ? 'open' : 'closed'">Content</div>',
  animations: [
    trigger('openClose', [
      state('open', style({
        height: '200px',
        opacity: 1,
        backgroundColor: 'yellow'
      })),
      state('closed', style({
        height: '100px',
        opacity: 0.5,
        backgroundColor: 'green'
      })),
      transition('open => closed', [
        animate('1s')
      ]),
      transition('closed => open', [
        animate('0.5s')
      ]),
    ]),
  ],
})
export class AnimateComponent {
  isOpen = true;
}

Security

Sanitizing HTML

import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Component({
  selector: 'app-sanitizer',
  template: '<div [innerHTML]="safeHtml"></div>'
})
export class SanitizerComponent {
  safeHtml: SafeHtml;

  constructor(private sanitizer: DomSanitizer) {
    const unsafeHtml = '<script>alert("XSS")</script> <b>Bold text</b>';
    this.safeHtml = this.sanitizer.bypassSecurityTrustHtml(unsafeHtml);
  }
}

Internationalization

Using ngx-translate

import { TranslateService } from '@ngx-translate/core';

export class AppComponent {
  constructor(private translate: TranslateService) {
    translate.setDefaultLang('en');
  }

  useLanguage(language: string) {
    this.translate.use(language);
  }
}
<h1>{{ 'TITLE' | translate }}</h1>
<button (click)="useLanguage('en')">English</button>
<button (click)="useLanguage('fr')">Français</button>

Optimizations

Lazy Loading

const routes: Routes = [
  { 
    path: 'customers', 
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  }
];

AOT Compilation

ng build --aot

2024 © All rights reserved - buraxta.com