Angular Cheat Sheet

AngularCLI

Command line inferface for Angular - set of commands that will help us during development.

1. Setup

Command

Description

npm install -g @angular/cli

Install Angular CLI globally

2. New application

Command

Description

ng new best-practises --dry-run

just simulate ng new

ng new best-practises --skip-install

skip install means don't run npm install

ng new best-practises --prefix best

set prefix to best

ng new --help

check available command list

3. Lint - check and make sure that our code if free of code smells/ bad formatting

Command

Description

ng lint my-app --help

check available command list

ng lint my-app --format stylish

format code

ng lint my-app --fix

fix code smells

ng lint my-app

show warnings

4. Blueprints

Command

Description

ng g c my-component --flat true

don't create new folder for this component

--inline-template (-t)

will the template be in .ts file?

--inline-style (-s)

will the style be in .ts file?

--spec

generate spec?

--prefix

assign own prefix

ng g d directive-name

create directive

ng g s service-name

create service

ng g cl models/customer

create customer class in models folder

ng g i models/person

create create interface in models folder

ng g e models/gender

create create ENUM gender in models folder

ng g p init-caps

create create pipe

5. Building&Serving

Command

Description

ng build

build app to /dist folder

ng build --aot

build app without code that we don't need (optimatization)

ng build --prod

build for production

ng serve -o

serve with opening a browser

ng serve --live-reload

reload when changes occur

ng serve -ssl

serving using SSL

6. Add new capabilities

Command

Description

ng add @angular/material

add angular material to project

ng g @angular/material:material-nav --name nav

create material navigation component

Components and Templates

Components are the most basic UI building block of an Angular app. An Angular app contains a tree of Angular components.

Sample component ts file

Component attributes

Attribute

Description

changeDetection

The change-detection strategy to use for this component.

viewProviders

Defines the set of injectable objects that are visible to its view DOM children

moduleId

The module ID of the module that contains the component

encapsulation

An encapsulation policy for the template and CSS styles

interpolation

Overrides the default encapsulation start and end delimiters ({{ and }}

entryComponents

A set of components that should be compiled along with this component.

preserveWhitespaces

True to preserve or false to remove potentially superfluous whitespace characters from the compiled template.

Component life cycles

Life cycle

Description

ngOnInit

Called once, after the first ngOnChanges()

ngOnChanges

Called before ngOnInit() and whenever one of input properties change.

ngOnDestroy

Called just before Angular destroys the directive/component

ngDoCheck

Called during every change detection run

ngAfterContentChecked

Called after the ngAfterContentInit() and every subsequent ngDoCheck()

ngAfterViewChecked

Called after the ngAfterViewInit() and every subsequent ngAfterContentChecked().

ngAfterContentInit

Called once after the first ngDoCheck().

ngAfterViewInit

Called once after the first ngAfterContentChecked().

Template syntax

Syntax

Description

{{user.name}}

Interpolation - just generate user name here

<img [src] = "user.imageUrl">

property binding - bind image url for user to src attribute

<button (click)="do()" ... />

Event - assign function to click event

<button *ngIf="user.showSth" ... />

Show button when user.showSth is true

*ngFor="let item of items"

Iterate through items list

<div [ngClass]="{green: isTrue(), bold: itTrue()}"/>

Angular ngClass attribute

<div [ngStyle]="{'color': isTrue() ? '#bbb' : '#ccc'}"/>

Angular ngStyle attribute

Input and Output

Input() To pass value into child component

Sample child component implementation

Sample parent component usage

Output() Emiting event to parent component

Sample child component

Sample parent component

onRemoved in child component is calling someFunction in parent component

Content projection

Content projection is injection inner html into child component

Example:

Parent component template

Child component template

(some html here) will be injection into

Two differents htmls

ViewChild decorator

In order to have access to child component/directive/element

Sample for element: html:

component:

Instead of ElementRef can be used specific element like FormControl for forms.

Reference to element in html:

Routing

The Angular Router enables navigation from one view to the next as users perform application tasks.

Sample routing ts file

Then this should be added inside Angular.module imports

You can also turn on console tracking for your routing by adding enableTracing

Usage

routerLinkActive="active" will add active class to element when the link's route becomes active

CanActivate and CanDeactivate

Interface that a class can implement to be a guard deciding if a route can be activated. If all guards return true, navigation will continue.

and assing it in routing module:

Modules

Angular apps are modular and Angular has its own modularity system called NgModules. NgModules are containers for a cohesive block of code dedicated to an application domain, a workflow, or a closely related set of capabilities.

Sample module with comments

Services

Components shouldn't fetch or save data directly and they certainly shouldn't knowingly present fake data. They should focus on presenting data and delegate data access to a service.

Sample service with one function

Usage It should be injected before usage

and add in module:

HttpClient

To handle and consume http requests

  1. Add import to module

  1. Usage

Dependency Injection

Inject class into another class

It accepts 'root' as a value or any module of your application

Declare global values

class:

module:

usage (for example in component)

Pipes

Transform data/value to specific format, for example:

Show date in shortDate format:

Pipe implementation

usage

Directives

An Attribute directive changes the appearance or behavior of a DOM element. For example [ngStyle] is a directive

Custom directive

Usage

Animations

Animations - moving from style state to another style state. Before add BrowserModule and BrowserAnimationsModule to module

Implementation:

usage

Angular Forms

Template driven forms

Form logic (validation, properties) are kept in template

sample html

sample component

Reactive forms

Form logic (validation, properties) are kept in component

sample html

sample component

Custom Validator for Reactive forms

Function

Usage

Multi-field validation

Multi-field validation usage*

Error handling

Custom Validator Directive for Template driven forms

To register our custom validation directive to NG_VALIDATORS service we have to do it like this: (thanks to multi parameter we won't override NG_VALIDATORS but just add CustomValidator to NG_VALIDATORS)

Example:

For multiple fields:

ngModel in custom component

  1. Add to module:

  1. Implement ControlValueAccessor interface

Function

Description

registerOnChange

Register a function to tell Angular when the value of the input changes

registerOnTouched

Register a function to tell Angular when the value was touched

writeValue

tell Angular how to Write a value to the input

Sample implementation:

Tests

Unit tests

Service

For async functions

example async test:

Spy and stub

Spy:

Stub:

TestBed Mock whole module/environment for unit tests

Then use tested object (for example service) like this:

we can add schemas: [NO_ERRORS_SCHEMA]. This means that we don’t have to mock children component dependencies of this component as Angular won’t yell at us anymore for our lack of doing so.

Others

Http interceptor

Intercepts and handles an HttpRequest or HttpResponse.

Class:

Module:

host

Refer to host element/component

Value

Description

:host(selector) { ... }

to match attributes, classes on the host element and add styling to it

:host-context(selector) { ... }

to match elements, classes on parent components and add styling to it

:host ::ng-deep

styling will be applied also to all child components

Interview questions

When would you use the useFactory provider method?

With useFactory we can use a factory at runtime to decide which kind of service we want to return if it got requested by any other class in our application or you need to parameterize the construction of a service

Service1 will be injected into another class

What is router-outlet

Acts as a placeholder that Angular dynamically fills based on the current router state. Generally in place of your main app component will be generated

How to declare global value?

Use InjectionToken

Which decorator lets you inject a service registered with an Injection Token?

@Inject

for example

How to mimick environment for components/services in tests?

Use TestBed. See Unit tests

What is Resolve interface?

Interface that classes can implement to be a data provider for component while routing.

example:

We can use it to pre-load data for a component before the component is displayed

How to begin validation after the user will enter a value and pause?

Use debounceTime, for example

What is valueChanges in form control?

To catch value changes and implement some logic in observable result. See example above

How to execute canActivate if any of child routes will change?

Use canActivateChild

What are compilation types in Angular?

Type

Description

AoT

Ahead of time - compile full application / module when application was opened. Used mainly on production

JiT

Just in time - compile specific element when it has been opened. Used mainly while programming

Ivy

Since Angular 8 - engine based on concept Incremental DOM

What is ng-content in Angular?

See ng-content

How to create application with cutom prefix?

What is module lazy loading?

Instead of loading all modules while app starts we can load particular module when needed.

This is usually used for big apps in order to improve performance

Why should we consider using ngIf instead of ngClass/ngStyle for hiding element?

ngIf won't generate element when condition result is fale, so html will be lighter. ngClass/ngStyle will just hide element but it will be still existing in DOM

What is Done() function in tests?

We need 'done' to avoid test finishing before date was received See done

What "import", "providers" and "declarations" stand for in NgModule?

See Sample module

Explain the difference between Constructor and ngOnInit

Constructor is a method assigned to a class, so it is called when class object was initialized. ngOnInit is part of Component life cycle and it is dependent on the current state of view initialization. Constructor is called before ngOnInit

What is a difference between ElementRef and TemplateRef?

ElementRef is reference to particular element while TemplateRef can refer to whole ng-template

Point all data biding ways for element

Bindint type

Example

Property binding

[src]="this.src"

Event binding

(click)="this.doSth()"

Two way data bidning

[(ngModel)]="this.form.userName"

How to handle ngModel property in custom component?

Implement ControlValueAccessor interface. See ngModel

What is differenct between default and onPush change detector?

default change detector will check bidnings in whole application component tree after event OnPush change detector informs Angular that our component biding is depend on input parameters. Moreover it won't check bindings in whole application but only in subtree where our component belongs.

Why is it better to use pure pipes instead of some functions in template view?

If we want to calculate for example user age and show it on template then we can do it with function:

But it will be calculated every time when change detector is run, so it can affect on performance. Instead we can use pipe for that:

Now age calculation won't be performed so many times.

How to detect change for any @Input property?

Use ngOnChanges hook

How to detect change for specific @Input in component?

Use 'set' accessor

Last updated

Was this helpful?