Language: EN

cheatsheet-angular

Angular Cheatsheet

Angular is a JavaScript framework developed by Google for building single-page web applications (SPA).

It is based on the MVC (Model-View-Controller) concept and allows for the development of dynamic and highly interactive applications.

Installation and Setup

Install Angular CLI

The Angular CLI makes it easier to create and maintain Angular projects.

npm install -g @angular/cli

Check Angular CLI version

ng version

Generate an Angular project

Create a new project using the Angular CLI.

ng new project-name

Run the development server

Start the development server on localhost:4200.

ng serve

Fundamentals

Initialize an Angular application

To initialize your application, use the ng-app directive in your HTML:

<div ng-app="myApp">
    <!-- Content here -->
</div>

Define a module

Modules are the foundation of any Angular application. They are defined as follows:

var app = angular.module('myApp', []);

Components

Components are a modern way to create directives that encapsulate both logic and view.

Generate a component

Use the CLI to generate a component.

ng generate component component-name

Basic components

Each component has:

  • An HTML file for the view.
  • A TypeScript file for the logic.
  • A CSS/SCSS file for the styles.
import { Component } from '@angular/core';

@Component({
  selector: 'app-component-name',
  templateUrl: './component-name.component.html',
  styleUrls: ['./component-name.component.css']
})

export class ComponentNameComponent {
  title = 'Hello Angular';
}

Use a component in HTML

<my-component></my-component>

Data Binding

Data Interpolation

Used to display data in the view from the component.

<h1>{{ title }}</h1>

Property Binding

To bind HTML element properties to component variables.

<img [src]="imageURL">

Event Binding

To capture events like button clicks.

<button (click)="myFunction()">Click Me</button>

Two-way Data Binding

To bind model and view data simultaneously, use ngModel.

<input [(ngModel)]="name">
export class AppComponent {
  name: string = '';
}

Filters

What are filters?

Filters are used to format data in views. Angular provides several built-in filters, such as currency, date, and filter.

Using filters in HTML

<p>Price: {{ price | currency }}</p>
<p>Date: {{ date | date:'fullDate' }}</p>

Directives

Directives are markers on the DOM that tell Angular to behave in a specific way.

ng-model

<input type="text" ng-model="name">
<p>Hello, {{ name }}!</p>

ng-repeat

Iterates over a collection

<ul>
    <li ng-repeat="item in items">{{ item }}</li>
</ul>

ng-if

Conditionally includes an element in the DOM Condition to show or hide elements.

<p *ngIf="show">This text will be shown if `show` is true</p>

ngFor

To iterate over lists of elements.

<li *ngFor="let item of items">{{ item }}</li>

ngClass

Dynamically applies classes.

<div [ngClass]="{'active-class': condition}">Content</div>

ngStyle

Dynamically applies styles.

<div [ngStyle]="{'color': colorVariable}">Dynamically colored text</div>

Controllers

Create a controller

Controllers are responsible for business logic and data manipulation:

app.controller('MyController', function($scope) {
    $scope.message = "Hello, Angular!";
});

Use a controller in HTML

To bind a controller to a part of your HTML:

<div ng-controller="MyController">
    <p>{{ message }}</p>
</div>

Services and Dependency Injection

Services are singleton objects that can be used throughout the application. They are used to handle business logic and share data between controllers.

Creating a service

Services handle business logic and are injected into components.

ng generate service service-name

Define a service

app.service('MyService', function() {
    this.message = "Hello from the service!";
});

Inject a service into a controller

app.controller('MyController', function($scope, MyService) {
    $scope.message = MyService.message;
});

Inject a service into a component

Use the @Injectable() decorator and add the service to the component’s constructor.

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

@Injectable({
  providedIn: 'root'
})
export class MyService {
  getData() {
    return ['data1', 'data2', 'data3'];
  }
}

import { MyService } from './my-service.service';

export class AppComponent {
  data: string[];

  constructor(private service: MyService) {
    this.data = service.getData();
  }
}

Routing

Route Configuration

Configure routes in the app-routing.module.ts file.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { DetailComponent } from './detail/detail.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'detail/:id', component: DetailComponent }
];

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

To navigate between routes within the application.

<a [routerLink]="['/detail', item.id]">View details</a>

Activate navigation from code

import { Router } from '@angular/router';

constructor(private router: Router) {}

this.router.navigate(['/desired-route']);

Forms

Creating forms

Angular supports reactive forms for complex validations.

import { FormGroup, FormControl, Validators } from '@angular/forms';

export class AppComponent {
  form = new FormGroup({
    name: new FormControl('', Validators.required),
    email: new FormControl('', [Validators.required, Validators.email])
  });
}

Form in the view

<form [formGroup]="form" (ngSubmit)="submit()">
  <input formControlName="name" placeholder="Name">
  <input formControlName="email" placeholder="Email">
  <button type="submit" [disabled]="form.invalid">Submit</button>
</form>

Validations

Validations can be applied to form controls.

this.form = new FormGroup({
  name: new FormControl('', [Validators.required, Validators.minLength(4)])
});

Show error messages

<div *ngIf="form.get('name').invalid && form.get('name').touched">
  Name is required and must be at least 4 characters long.
</div>

Interaction with APIs

HTTP Client

The HttpClient service allows for making HTTP requests.

import { HttpClient } from '@angular/common/http';

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

  getData() {
    return this.http.get('https://api.my-server.com/data');
  }
}

Making a GET request

this.myService.getData().subscribe(data => {
  console.log(data);
});

State Management with NgRx

Actions

Define what happens in the application.

export const increment = createAction('[Counter] Increment');

Reducers

Manage the state according to the actions.

const _counterReducer = createReducer(initialState,
  on(increment, state => state + 1)
);

export function counterReducer(state, action) {
  return _counterReducer(state, action);
}

Selectors

Access the state.

export const selectCounter = createSelector(
  (state: AppState) => state.counter
);

Testing in Angular

Run unit tests

Angular uses Karma and Jasmine for unit testing.

ng test

Example of a unit test

it('should return true when the form is valid', () => {
  component.form.controls['name'].setValue('Luis');
  expect(component.form.valid).toBeTruthy();
});