Cheat Sheet

Angular Cheat Sheet


1. Angular CLI Commands


ng new project-name       // Create a new Angular project
ng serve                  // Start the development server
ng build                  // Build the project for production
ng generate component x   // Generate a new component
ng generate service x     // Generate a new service
ng generate module x      // Generate a new module
ng test                   // Run unit tests
ng lint                   // Run linting
ng update                 // Update Angular dependencies

2. Components


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'My App';
}

3. Directives


*ngIf=`condition`         // Conditional rendering
*ngFor=`let item of items` // Loop through items
[ngClass]=`{'class': condition}` // Conditional class binding
[ngStyle]=`{'color': 'red'}`     // Inline style binding

4. Data Binding


{{ expression }}          // Interpolation (one-way)
[property]=`expression`   // Property binding (one-way)
(event)=`handler()`       // Event binding (one-way)
[(ngModel)]=`property`    // Two-way data binding

5. Services


@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor() {}
  getData() { return 'Data'; }
}

6. Dependency Injection


constructor(private service: MyService) {}

7. Routing


const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

8. Forms


<form [formGroup]=`myForm` (ngSubmit)=`onSubmit()`>
  <input formControlName=`name` />
  <button type=`submit`>Submit</button>
</form>
this.myForm = this.fb.group({
  name: ['', Validators.required]
});

9. HTTP Client


import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) {}
this.http.get('https://api.example.com/data').subscribe(data => {
  console.log(data);
});

10. Pipes


{{ value | date }}        // Format date
{{ value | uppercase }}   // Convert to uppercase
{{ value | currency }}    // Format as currency
{{ value | json }}        // Convert to JSON

11. Lifecycle Hooks


ngOnInit() {}             // Called after the component is initialized
ngOnChanges() {}          // Called when input properties change
ngOnDestroy() {}          // Called before the component is destroyed

12. Modules


@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

13. Guards


@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  canActivate(): boolean {
    return true; // Logic to allow/deny access
  }
}

14. Interceptors


@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authReq = req.clone({ headers: req.headers.set('Authorization', 'token') });
    return next.handle(authReq);
  }
}

15. RxJS Operators


import { map, filter, tap } from 'rxjs/operators';
this.http.get('url').pipe(
  map(data => data),
  filter(data => data.length >  0),
  tap(data => console.log(data))
).subscribe();

16. Observables


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

17. Async Pipe


<div *ngIf=`data$ | async as data`>
  {{ data }}
</div>

18. Template Reference Variables


<input #myInput />
<button (click)=`doSomething(myInput.value)`>Submit</button>

19. Event Emitters


@Output() myEvent = new EventEmitter<string>();
this.myEvent.emit('Hello');

20. NgModule Imports


import { FormsModule } from '@angular/forms';
@NgModule({
  imports: [FormsModule]
})
export class AppModule {}

21. Custom Pipes


import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'customPipe' })
export class CustomPipe implements PipeTransform {
  transform(value: string): string {
    return value.toUpperCase();
  }
}

22. TrackBy in ngFor


<div *ngFor=`let item of items; trackBy: trackByFn`>
  {{ item.name }}
</div>
trackByFn(index: number, item: any): number {
  return item.id; // or unique identifier
}

23. ViewChild


@ViewChild('myInput') myInput: ElementRef;
ngAfterViewInit() {
  this.myInput.nativeElement.focus();
}

24. Content Projection


<ng-content></ng-content> // Use in component template

25. Angular Animations


import { trigger, state, style, transition, animate } from '@angular/animations';
@Component({
  animations: [
    trigger('myAnimation', [
      state('start', style({ opacity: 0 })),
      state('end', style({ opacity: 1 })),
      transition('start => end', animate('500ms ease-in'))
    ])
  ]
})

26. NgIf with Else


<div *ngIf=`condition; else elseBlock`>Content</div>
<ng-template #elseBlock>Else Content</ng-template>

27. NgSwitch


<div [ngSwitch]=`value`>
  <div *ngSwitchCase=`'A'`>Case A</div>
  <div *ngSwitchCase=`'B'`>Case B</div>
  <div *ngSwitchDefault>Default Case</div>
</div>

28. Angular Material


import { MatButtonModule } from '@angular/material/button';
@NgModule({
  imports: [MatButtonModule]
})
export class AppModule {}

29. Lazy Loading Modules


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

30. Angular Universal


import { AppServerModule } from './app/app.server.module';
export { AppServerModule };

31. Change Detection


import { ChangeDetectorRef } from '@angular/core';
constructor(private cdr: ChangeDetectorRef) {}
someMethod() {
  this.cdr.detectChanges();
}

32. NgZone


import { NgZone } from '@angular/core';
constructor(private zone: NgZone) {}
this.zone.run(() => {
  // Code to run inside Angular zone
});

33. Angular Ivy


ng build --prod // Enable Ivy by default in Angular 9+

34. Service Workers


ng add @angular/pwa // Add PWA support

35. Service Worker Registration


if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/ngsw-worker.js').then(registration => {
      console.log('Service Worker registered with scope:', registration.scope);
    });
  });
}

36. Angular Environment Variables


export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000'
};

37. Custom Validators


import { AbstractControl, ValidatorFn } from '@angular/forms';
export function customValidator(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const valid = /* validation logic */;
    return valid ? null : { 'customError': { value: control.value } };
  };
}

38. Reactive Forms


import { FormGroup, FormBuilder } from '@angular/forms';
this.myForm = this.fb.group({
  name: [''],
  age: ['']
});

39. Template-Driven Forms


<form #myForm=`ngForm`>
  <input name=`name` ngModel />
  <button [disabled]=`!myForm.valid`>Submit</button>
</form>

40. NgModel


<input [(ngModel)]=`property` />

41. FormArray


this.myForm = this.fb.group({
  items: this.fb.array([])
});
get items(): FormArray {
  return this.myForm.get('items') as FormArray;
}

42. FormBuilder


constructor(private fb: FormBuilder) {}

43. Validators


import { Validators } from '@angular/forms';
this.myForm = this.fb.group({
  name: ['', Validators.required],
  email: ['', [Validators.required, Validators.email]]
});

44. NgFor with Index


<div *ngFor=`let item of items; let i = index`>
  {{ i }}: {{ item }}
</div>

45. NgClass with Multiple Classes


<div [ngClass]=`{'class1': condition1, 'class2': condition2}`>Content</div>

46. NgStyle with Multiple Styles


<div [ngStyle]=`{'color': color, 'font-size': size}`>Styled Content</div>

47. HostListener


@HostListener('click', ['$event'])
onClick(event: MouseEvent) {
  console.log('Element clicked:', event);
}

48. HostBinding


@HostBinding('class.active') isActive = true;

49. NgIf with Async Pipe


<div *ngIf=`data$ | async as data`>{{ data }}</div>

50. NgTemplateOutlet


<ng-container *ngTemplateOutlet=`templateRef`></ng-container>

51. Dynamic Component Loading


import { ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
const componentFactory = this.resolver.resolveComponentFactory(MyComponent);
this.container.createComponent(componentFactory);

52. Change Detection Strategy


@Component({
  changeDetection: ChangeDetectionStrategy.OnPush
})

53. NgZone.runOutsideAngular


this.zone.runOutsideAngular(() => {
  // Code to run outside Angular's zone
});

54. Angular Lifecycle Hooks


ngOnInit() {}
ngOnChanges() {}
ngOnDestroy() {}

55. Angular Pipes


import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'myPipe' })
export class MyPipe implements PipeTransform {
  transform(value: any): any {
    return value; // Custom transformation logic
  }
}

56. NgIf with TrackBy


<div *ngFor=`let item of items; trackBy: trackByFn`>
  {{ item.name }}
</div>
trackByFn(index: number, item: any): number {
  return item.id; // Unique identifier
}

57. NgFor with Let


<div *ngFor=`let item of items; let i = index`>
  {{ i }}: {{ item }}
</div>

58. NgSwitch with Default Case


<div [ngSwitch]=`value`>
  <div *ngSwitchCase=`'A'`>Case A</div>
  <div *ngSwitchDefault>Default Case</div>
</div>

59. Angular Forms Validation


this.myForm = this.fb.group({
  name: ['', Validators.required],
  age: ['', [Validators.required, Validators.min(18)]]
});

60. FormGroup and FormControl


import { FormGroup, FormControl } from '@angular/forms';
this.myForm = new FormGroup({
  name: new FormControl(''),
  age: new FormControl('')
});

61. FormBuilder with FormArray


this.myForm = this.fb.group({
  items: this.fb.array([this.fb.control('')])
});

62. Reactive Forms with Validation


this.myForm = this.fb.group({
  email: ['', [Validators.required, Validators.email]]
});

63. Template-Driven Forms with Validation


<form #form=`ngForm`>
  <input name=`email` ngModel required email />
  <button [disabled]=`!form.valid`>Submit</button>
</form>

64. FormControl with Initial Value


this.myControl = new FormControl('Initial Value');

65. FormArray with Dynamic Controls


addItem() {
  this.items.push(this.fb.control(''));
}

66. Custom Form Control


import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => CustomInputComponent),
    multi: true
  }]
})
export class CustomInputComponent implements ControlValueAccessor {
  writeValue(value: any): void {}
  registerOnChange(fn: any): void {}
  registerOnTouched(fn: any): void {}
}

67. Angular Material Dialog


import { MatDialog } from '@angular/material/dialog';
constructor(private dialog: MatDialog) {}
openDialog() {
  this.dialog.open(MyDialogComponent);
}

68. Angular Material Snackbar


import { MatSnackBar } from '@angular/material/snack-bar';
constructor(private snackBar: MatSnackBar) {}
openSnackBar(message: string) {
  this.snackBar.open(message, 'Close', { duration: 2000 });
}

69. Angular Material Table


import { MatTableDataSource } from '@angular/material/table';
dataSource = new MatTableDataSource(data);

70. Angular Material Pagination


import { MatPaginator } from '@angular/material/paginator';
@ViewChild(MatPaginator) paginator: MatPaginator;
ngAfterViewInit() {
  this.dataSource.paginator = this.paginator;
}

71. Angular Material Sort


import { MatSort } from '@angular/material/sort';
@ViewChild(MatSort) sort: MatSort;
ngAfterViewInit() {
  this.dataSource.sort = this.sort;
}

72. Angular Material Form Field


<mat-form-field>
  <input matInput placeholder=`Enter your name`>
</mat-form-field>

73. Angular Material Button

 
<button mat-button>Click me!</button>

74. Angular Material Checkbox


<mat-checkbox>Check me!</mat-checkbox>

75. Angular Material Radio Button


<mat-radio-group>
  <mat-radio-button value=`1`>Option 1</mat-radio-button>
  <mat-radio-button value=`2`>Option 2</mat-radio-button>
</mat-radio-group>

76. Angular Material Select


<mat-form-field>
  <mat-select placeholder=`Select an option`>
    <mat-option value=`1`>Option 1</mat-option>
    <mat-option value=`2`>Option 2</mat-option>
  </mat-select>
</mat-form-field>

77. Angular Material Tooltip


<button mat-button matTooltip=`Tooltip message`>Hover me!</button>

78. Angular Material Icon


<mat-icon>home</mat-icon>

79. Angular Material Card


<mat-card>
  <mat-card-title>Card Title</mat-card-title>
  <mat-card-content>Card content goes here.</mat-card-content>
</mat-card>

80. Angular Material Grid List


<mat-grid-list cols=`2` rowHeight=`2:1`>
  <mat-grid-tile>Tile 1</mat-grid-tile>
  <mat-grid-tile>Tile 2</mat-grid-tile>
</mat-grid-list>

81. Angular Material Stepper


<mat-horizontal-stepper>
  <mat-step label=`Step 1`>Content 1</mat-step>
  <mat-step label=`Step 2`>Content 2</mat-step>
</mat-horizontal-stepper>

82. Angular Material Datepicker


<mat-form-field>
  <input matInput [matDatepicker]=`picker`>
  <mat-datepicker-toggle matSuffix [for]=`picker`></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

83. Angular Material Slider


<mat-slider min=`1` max=`100` step=`1` value=`50`></mat-slider>

84. Angular Material Progress Bar


<mat-progress-bar mode=`determinate` value=`40`></mat-progress-bar>

85. Angular Material Progress Spinner


<mat-spinner></mat-spinner>

86. Angular Material Divider


<mat-divider></mat-divider>

87. Angular Material Expansion Panel


<mat-accordion>
  <mat-expansion-panel>
    <mat-expansion-panel-header>
      <mat-panel-title>Expansion Panel Title</mat-panel-title>
    </mat-expansion-panel-header>
    <p>Expansion panel content</p>
  </mat-expansion-panel>
</mat-accordion>

88. Angular Material List


<mat-list>
  <mat-list-item>Item 1</mat-list-item>
  <mat-list-item>Item 2</mat-list-item>
</mat-list>

89. Angular Material Menu


<button mat-button [matMenuTriggerFor]=`menu`>Menu</button>
<mat-menu #menu>
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

90. Angular Material Snackbar with Action


this.snackBar.open('Message', 'Action', {
  duration: 2000,
  panelClass: ['custom-snackbar']
});

91. Angular Material Chips


<mat-chip-list>
  <mat-chip>Chip 1</mat-chip>
  <mat-chip>Chip 2</mat-chip>
</mat-chip-list>

92. Angular Material Badge


<span matBadge=`4`>Notifications</span>

93. Angular Material Bottom Sheet


this.bottomSheet.open(MyBottomSheetComponent);

94. Angular Material Tree


<mat-tree [dataSource]=`dataSource` [treeControl]=`treeControl`>
  <mat-tree-node *matTreeNodeDef=`let node` matTreeNodeToggle>{{ node.item }}</mat-tree-node>
</mat-tree>

95. Angular Material Tabs


<mat-tab-group>
  <mat-tab label=`Tab 1`>Content 1</mat-tab>
  <mat-tab label=`Tab 2`>Content 2</mat-tab>
</mat-tab-group>

96. Angular Material Stepper with Forms


<mat-horizontal-stepper>
  <mat-step [stepControl]=`firstFormGroup`>
    <form [formGroup]=`firstFormGroup`>
      <ng-template matStepLabel>Step 1</ng-template>
      <mat-form-field>
        <input matInput placeholder=`Input`>
      </mat-form-field>
      <div>
        <button mat-button matStepperNext>Next</button>
      </div>
    </form>
  </mat-step>

97. Angular Material Datepicker with Form Control


<mat-form-field>
  <input matInput [matDatepicker]=`picker` formControlName=`date`>
  <mat-datepicker-toggle matSuffix [for]=`picker`></mat-datepicker-toggle>
  <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

98. Angular Material Datepicker with Custom Format


import { DateAdapter, MatDateFormats, MAT_DATE_FORMATS } from '@angular/material/core';
export const MY_DATE_FORMATS: MatDateFormats = {
  parse: {
    dateInput: 'DD/MM/YYYY',
  },
  display: {
    dateInput: 'DD/MM/YYYY',
    monthYearLabel: 'MMM YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'MMMM YYYY',
  },
};
providers: [
  { provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS },
]

99. Angular Material Grid List with Responsive Layout


<mat-grid-list cols=`2` rowHeight=`2:1` gutterSize=`10px`>
  <mat-grid-tile>Tile 1</mat-grid-tile>
  <mat-grid-tile>Tile 2</mat-grid-tile>
</mat-grid-list>

100. Angular Material Theming


@import '~@angular/material/theming';
@include mat-core();
$primary: mat-palette($mat-indigo);
$accent: mat-palette($mat-pink);
$theme: mat-light-theme($primary, $accent);
@include angular-material-theme($theme);

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.