Angular Cheatsheet - Essential Syntax & Concepts

Comprehensive Angular cheatsheet covering bootstrapping, modules, template syntax, directives, forms, decorators, and routing. Your go-to Angular reference.

Angular Cheatsheet

This Angular cheatsheet provides a quick reference for essential concepts and syntax for Angular (version 2 and above). It's based on the official documentation and style guide, making it a valuable resource for developers working with the framework.

Angular CLI Installation and Usage

The Angular CLI (Command Line Interface) is a powerful tool for initializing, developing, scaffolding, and maintaining Angular applications. Here are some fundamental commands:


npm install -g @angular/cli       # Install Angular CLI globally
ng new my-angular-app             # Create a new Angular workspace and initial application
cd my-angular-app                 # Navigate into the project directory
ng serve                          # Build and serve the app locally for development
ng build                          # Build the application for production deployment
                
Bootstrapping an Angular Application

Bootstrapping is the process of initializing the Angular application. It typically involves using platformBrowserDynamic to launch the root module.


import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module'; // Assuming your root module is AppModule

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));
                
Angular Modules (NgModules)

NgModules are containers for a cohesive block of code dedicated to a particular domain, application feature, or workflow. They help organize your application and manage dependencies.


import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MyRedComponent } from './my-red.component';
import { MyDatePipe } from './my-date.pipe';
import { MyService } from './my.service';

@NgModule({
  declarations: [
    MyRedComponent, // Components, directives, and pipes belonging to this module
    MyDatePipe
  ],
  imports: [
    BrowserModule, // Other modules this module depends on
    // OtherModule
  ],
  exports: [
    MyRedComponent, // Components, directives, and pipes visible to modules that import this module
    MyDatePipe
  ],
  providers: [
    MyService, // Services available for dependency injection
    // { provide: SomeToken, useValue: 'someValue' }
  ],
  bootstrap: [
    // MyAppComponent // The root component to bootstrap if this is the root module
  ]
})
export class MyFeatureModule {}
                
Template Syntax

Angular's template syntax allows you to bind data, handle events, and control the DOM within your HTML.

  • Property Binding: Binds a property value to the result of an expression.
    <input [value]="firstName">
  • Attribute Binding: Binds an attribute to the result of an expression.
    <div [attr.role]="myAriaRole">
  • Class Binding: Conditionally applies CSS classes.
    <div [class.extra-sparkle]="isDelightful">
  • Style Binding: Conditionally applies CSS styles.
    <div [style.width.px]="mySize">
  • Event Binding: Calls a method when an event is triggered.
    <button (click)="readRainbow($event)">
  • Interpolation: Displays a property value as text.
    <div title="Hello {{ponyName}}">
    <p>Hello {{ponyName}}</p>
  • Two-Way Data Binding: Combines property and event binding for seamless data flow.
    <my-cmp [(title)]="name">
  • Template Reference Variable: Creates a local variable to access DOM elements or component instances.
    <video #movieplayer ...>
    <button (click)="movieplayer.play()">
    </video>
  • Structural Directives: Modify the DOM structure. The asterisk (*) denotes a structural directive.
    <p *myUnless="myExpression">...</p>
  • Pipes: Transform data in templates.
    <p>Card No.: {{cardNumber | myCardNumberFormatter}}</p>
  • Safe Navigation Operator: Handles potentially null or undefined values gracefully.
    <p>Employer: {{employer?.companyName}}</p>
  • SVG Templates: Use the svg: prefix for SVG elements within templates.
    <svg:rect x="0" y="0" width="100" height="100"/>
    <svg>
    <rect x="0" y="0" width="100" height="100"/>
    </svg>
Built-in Directives

Angular provides several built-in directives for common tasks.

  • *ngIf: Conditionally renders an element.
    <section *ngIf="showSection">
  • *ngFor: Iterates over a collection to render elements.
    <li *ngFor="let item of list">
  • [ngSwitch], [ngSwitchCase], [ngSwitchDefault]: Renders different content based on a switch expression.
    <div [ngSwitch]="conditionExpression">
    <ng-template [ngSwitchCase]="case1Exp">...</ng-template>
    <ng-template ngSwitchCase="case2LiteralString">...</ng-template>
    <ng-template ngSwitchDefault>...</ng-template>
    </div>
  • [ngClass]: Dynamically adds or removes CSS classes.
    <div [ngClass]="{'active': isActive, 'disabled': isDisabled}">
  • [ngStyle]: Dynamically applies CSS styles.
    <div [ngStyle]="{'property': 'value'}">
    <div [ngStyle]="dynamicStyles()">
Forms

Angular supports two main approaches to forms: Template-driven and Reactive Forms. The FormsModule is used for template-driven forms.


import { FormsModule } from '@angular/forms';

// In your component's template:
// <input [(ngModel)]="userName">
                
Class Decorators

Decorators are used to add metadata to classes, enabling Angular to understand their role.

  • @Component: Marks a class as an Angular component.
    @Component({...})
    class MyComponent() {}
  • @Directive: Marks a class as an Angular directive.
    @Directive({...})
    class MyDirective() {}
  • @Pipe: Marks a class as an Angular pipe.
    @Pipe({...})
    class MyPipe() {}
  • @Injectable: Marks a class as a potential service to be provided and injected.
    @Injectable()
    class MyService() {}
Directive and Component Configuration

Directives and components share configuration options, including selectors and providers.


@Directive({
  selector: '.cool-button:not(a)', // CSS selector to identify the directive
  providers: [MyService]          // Providers scoped to this directive and its children
})
export class CoolButtonDirective {
  // ...
}
                
Component Configuration Specifics

Components have additional configuration options related to their templates and styles.


@Component({
  selector: 'my-component',
  template: 'Hello {{name}}', // Inline template
  templateUrl: 'my-component.html', // External template file
  styles: ['.primary {color: red}'], // Inline styles
  styleUrls: ['my-component.css'], // External stylesheet URLs
  moduleId: module.id, // Resolves templateUrl and styleUrls relative to the component
  viewProviders: [MyService] // Providers scoped to the component's view
})
export class MyComponent {
  // ...
}
                
Class Field Decorators

These decorators are used within directive and component classes to define inputs, outputs, and interact with the host element or content/view children.

  • @Input(): Declares a property that can be passed into the component/directive from its parent.
    @Input() myProperty;
  • @Output(): Declares an event emitter for communicating events from the component/directive to its parent.
    @Output() myEvent = new EventEmitter();
  • @HostBinding(): Binds a host element property (e.g., class, style) to a directive/component property.
    @HostBinding('class.valid') isValid;
  • @HostListener(): Subscribes to host element events.
    @HostListener('click', ['$event']) onClick(e) {...}
  • @ContentChild() / @ContentChildren(): Queries for elements projected into the component's content.
    @ContentChild(myPredicate) myChildComponent;
    @ContentChildren(myPredicate) myChildComponents;
  • @ViewChild() / @ViewChildren(): Queries for elements within the component's own template.
    @ViewChild(myPredicate) myChildComponent;
    @ViewChildren(myPredicate) myChildComponents;
Lifecycle Hooks

Angular components and directives go through a lifecycle. These hooks allow you to tap into specific moments in this lifecycle.

  • constructor(): For dependency injection.
  • ngOnChanges(changes): Called before ngOnInit and whenever one or more data-bound input properties change.
  • ngOnInit(): Called once after the first ngOnChanges. Good for initialization logic.
  • ngDoCheck(): Called during every change detection run. Use for custom change detection.
  • ngAfterContentInit(): Called after content (<ng-content>) is initialized.
  • ngAfterContentChecked(): Called after content is checked.
  • ngAfterViewInit(): Called once after the component's views are initialized.
  • ngAfterViewChecked(): Called after the component's views are checked.
  • ngOnDestroy(): Called just before Angular destroys the component or directive. Use for cleanup.
Dependency Injection Configuration

Angular's dependency injection system allows you to provide and inject services and values.


// Example of providing a service with a mock implementation
{ provide: MyService, useClass: MyMockService }

// Example of providing a service using a factory function
{ provide: MyService, useFactory: myFactory }

// Example of providing a constant value
{ provide: MyValue, useValue: 41 }
                
Routing and Navigation

The Angular Router enables navigation between different views and components in your application.


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

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'user/:id', component: UserDetailComponent },
  { path: 'products', loadChildren: () => import('./products/products.module').then(m => m.ProductsModule) },
  { path: '**', component: NotFoundComponent }, // Wildcard route for 404
  { path: 'old-path', redirectTo: '/new-path', pathMatch: 'full' }
];

// In your root module:
// @NgModule({
//   imports: [RouterModule.forRoot(routes)],
//   exports: [RouterModule]
// })
// export class AppRoutingModule { }

// In your component template:
// <router-outlet></router-outlet> // Placeholder for routed components

// <a routerLink="/user/123">View User</a>
// <a [routerLink]="['/user', userId]">Dynamic User</a>
// <a routerLink="/products" routerLinkActive="active-link">Products</a>

// Route Guards (e.g., CanActivate, CanDeactivate, CanLoad) are used to control navigation.
// Example:
// {
//   path: 'admin',
//   loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule),
//   canLoad: [AuthGuard] // Guard to check if the module can be loaded
// }
                
External Resources