0% found this document useful (0 votes)
527 views9 pages

Angular - Cheat Sheet

This document provides a summary of key Angular concepts including NgModules, template syntax, built-in directives, forms, class decorators, and directive/component configuration. It covers core Angular features for defining modules, binding to templates, built-in directives like NgIf and NgFor, and essential decorators.

Uploaded by

Iván Peralta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
527 views9 pages

Angular - Cheat Sheet

This document provides a summary of key Angular concepts including NgModules, template syntax, built-in directives, forms, class decorators, and directive/component configuration. It covers core Angular features for defining modules, binding to templates, built-in directives like NgIf and NgFor, and essential decorators.

Uploaded by

Iván Peralta
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

angular.

io

Angular - Cheat Sheet


12-15 minutos

import { NgModule } from


NgModules
'@angular/core';

@NgModule({
declarations: ...,
imports: ..., Defines a module that contains
exports: ..., components, directives, pipes, and
providers: ..., providers.

bootstrap: ...})
class MyModule {}
declarations:
[MyRedComponent, List of components, directives, and
MyBlueComponent, pipes that belong to this module.
MyDatePipe]
List of modules to import into this
imports:
module. Everything from the
[BrowserModule,
imported modules is available to
SomeOtherModule] declarations of this module.

exports: List of components, directives, and


[MyRedComponent, pipes visible to modules that import
MyDatePipe] this module.

List of dependency injection


providers: [MyService, providers visible both to the
{ provide: ... }] contents of this module and to
importers of this module.

bootstrap: List of components to bootstrap


[MyAppComponent] when this module is bootstrapped.

Template syntax
Binds property value to the result of
<input [value]="firstName">
expression firstName.
Binds attribute role to the result of
<div [attr.role]="myAriaRole">
expression myAriaRole.

Binds the presence of the CSS class


<div [class.extra- extra-sparkle on the element to
sparkle]="isDelightful"> the truthiness of the expression
isDelightful.

Binds style property width to the


<div [style.width.px]="mySize"> result of expression mySize in pixels.
Units are optional.

Calls method readRainbow when a


<button click event is triggered on this button
(click)="readRainbow($event)"> element (or its children) and passes in
the event object.

Binds a property to an interpolated


string, for example, "Hello Seabiscuit".
<div title="Hello {{ponyName}}"> Equivalent to: <div
[title]="'Hello ' +
ponyName">

Binds text content to an interpolated


<p>Hello {{ponyName}}</p>
string, for example, "Hello Seabiscuit".

Sets up two-way data binding.


Equivalent to: <my-cmp
<my-cmp [(title)]="name">
[title]="name"
(titleChange)="name=$event">

Creates a local variable


<video #movieplayer ...>
movieplayer that provides access
<button
to the video element instance in
(click)="movieplayer.play()">
data-binding and event-binding
</video>
expressions in the current template.

The * symbol turns the current


element into an embedded template.
<p
Equivalent to: <ng-template
*myUnless="myExpression">...</p>
[myUnless]="myExpression">
<p>...</p></ng-template>

Transforms the current value of


<p>Card No.: {{cardNumber |
expression cardNumber via the pipe
myCardNumberFormatter}}</p>
called myCardNumberFormatter.

The safe navigation operator (?)


<p>Employer: means that the employer field is
{{employer?.companyName}}</p> optional and if undefined, the rest of
the expression should be ignored.

An SVG snippet template needs an


<svg:rect x="0" y="0" svg: prefix on its root element to
width="100" height="100"/> disambiguate the SVG element from
an HTML component.

<svg>
An <svg> root element is detected as
<rect x="0" y="0" width="100"
an SVG element automatically,
height="100"/>
without the prefix.
</svg>

import {
Built-in directives CommonModule } from
'@angular/common';

Removes or recreates a
portion of the DOM tree
<section *ngIf="showSection"> based on the
showSection
expression.

Turns the li element and


its contents into a
<li *ngFor="let item of list"> template, and uses that to
instantiate a view for each
item in list.

<div
[ngSwitch]="conditionExpression">
<ng-template Conditionally swaps the
[ngSwitchCase]="case1Exp">...</ng- contents of the div by
template> selecting one of the
<ng-template embedded templates
ngSwitchCase="case2LiteralString">... based on the current
</ng-template> value of
conditionExpression.
<ng-template ngSwitchDefault>...
</ng-template>
</div>
Binds the presence of
CSS classes on the
element to the truthiness
<div [ngClass]="{'active': isActive, of the associated map
'disabled': isDisabled}"> values. The right-hand
expression should return
{class-name: true/false}
map.

Allows you to assign


styles to an HTML
<div [ngStyle]="{'property': element using CSS. You
'value'}"> can use CSS directly, as
<div [ngStyle]="dynamicStyles()"> in the first example, or you
can call a method from the
component.

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

Provides two-way data-binding,


<input
parsing, and validation for form
[(ngModel)]="userName">
controls.

import { Directive, ... } from


Class decorators
'@angular/core';

@Component({...})
Declares that a class is a component and
class
provides metadata about the component.
MyComponent() {}
@Directive({...})
Declares that a class is a directive and
class
provides metadata about the directive.
MyDirective() {}

@Pipe({...}) Declares that a class is a pipe and


class MyPipe() {} provides metadata about the pipe.

Declares that a class has dependencies


@Injectable()
that should be injected into the constructor
class MyService()
when the dependency injector is creating
{} an instance of this class.

@Directive({ property1:
Directive configuration
value1, ... })
Specifies a CSS selector that identifies
this directive within a template.
Supported selectors include element,
selector: '.cool-
[attribute], .class, and :not().
button:not(a)'
Does not support parent-child
relationship selectors.

providers:
List of dependency injection providers for
[MyService, {
this directive and its children.
provide: ... }]

@Component extends
@Directive, so the @Directive
Component configuration
configuration applies to
components as well

If set, the templateUrl and


moduleId: module.id styleUrl are resolved relative to
the component.

viewProviders: List of dependency injection


[MyService, { providers scoped to this component's
provide: ... }] view.

template: 'Hello
{{name}}' Inline template or external template
templateUrl: 'my- URL of the component's view.
component.html'
styles: ['.primary
List of inline CSS styles or external
{color: red}']
stylesheet URLs for styling the
styleUrls: ['my-
component’s view.
component.css']

Class field decorators for directives import { Input, ... } from


and components '@angular/core';

Declares an input property that you can


update via property binding (example:
@Input() myProperty; <my-cmp
[myProperty]="someExpression">).

Declares an output property that fires


@Output() myEvent = new events that you can subscribe to with an
EventEmitter(); event binding (example: <my-cmp
(myEvent)="doSomething()">).
Directive and component change (implemented as class
detection and lifecycle hooks methods)

Called before any other


constructor(myService: lifecycle hook. Use it to inject
MyService, ...) { ... } dependencies, but avoid any
serious work here.

Called after every change to


ngOnChanges(changeRecord) { input properties and before
... } processing content or child
views.

Called after the constructor,


initializing input properties,
ngOnInit() { ... }
and the first call to
ngOnChanges.

Called every time that the


input properties of a
component or a directive are
ngDoCheck() { ... }
checked. Use it to extend
change detection by
performing a custom check.

Called after ngOnInit when


ngAfterContentInit() { ...
the component's or directive's
}
content has been initialized.

Called after every check of


ngAfterContentChecked() {
the component's or directive's
... }
content.

Called after
ngAfterContentInit
ngAfterViewInit() { ... } when the component's view
has been initialized. Applies
to components only.

Called after every check of


ngAfterViewChecked() { ...
the component's view. Applies
}
to components only.

Called once, before the


ngOnDestroy() { ... }
instance is destroyed.

Dependency injection
configuration

{ provide: MyService, Sets or overrides the provider for


useClass: MyMockService MyService to the
} MyMockService class.

Sets or overrides the provider for


{ provide: MyService,
MyService to the myFactory
useFactory: myFactory }
factory function.

{ provide: MyValue, Sets or overrides the provider for


useValue: 41 } MyValue to the value 41.

import { Routes,
RouterModule, ...
Routing and navigation
} from
'@angular/router';

const routes: Routes = [


{ path: '', component: HomeComponent },
{ path: 'path/:routeParam', component:
Configures routes for
MyComponent },
the application.
{ path: 'staticPath', component: ... },
Supports static,
{ path: '**', component: ... },
parameterized, redirect,
{ path: 'oldPath', redirectTo:
and wildcard routes.
'/staticPath' },
Also supports custom
{ path: ..., component: ..., data: {
route data and resolve.
message: 'Custom' } }
]);
const routing = RouterModule.forRoot(routes);

Marks the location to


<router-outlet></router-outlet> load the component of
<router-outlet name="aux"></router-outlet> the active route.

Creates a link to a

<a routerLink="/path"> different view based on


a route instruction
<a [routerLink]="[ '/path', routeParam ]">
consisting of a route
<a [routerLink]="[ '/path', { matrixParam:
path, required and
'value' } ]">
optional parameters,
<a [routerLink]="[ '/path' ]"
query parameters, and a
[queryParams]="{ page: 1 }">
fragment. To navigate to
<a [routerLink]="[ '/path' ]"
a root route, use the /
fragment="anchor">
prefix; for a child route,
use the ./prefix; for a
sibling or parent, use
the ../ prefix.

The provided classes


are added to the
<a [routerLink]="[ '/path' ]"
element when the
routerLinkActive="active"> routerLink becomes
the current active route.

class CanActivateGuard implements CanActivate


{ An interface for defining
a class that the router
canActivate(
should call first to
route: ActivatedRouteSnapshot,
determine if it should
state: RouterStateSnapshot
activate this component.
):
Should return a boolean
Observable<boolean>|Promise<boolean>|boolean
or an
{ ... }
Observable/Promise
} that resolves to a
{ path: ..., canActivate: [CanActivateGuard] boolean.
}

class CanDeactivateGuard implements


CanDeactivate<T> { An interface for defining
a class that the router
canDeactivate(
should call first to
component: T,
determine if it should
route: ActivatedRouteSnapshot,
deactivate this
state: RouterStateSnapshot
component after a
):
navigation. Should
Observable<boolean>|Promise<boolean>|boolean
return a boolean or an
{ ... } Observable/Promise
} that resolves to a
{ path: ..., canDeactivate: boolean.
[CanDeactivateGuard] }

class CanActivateChildGuard implements An interface for defining


CanActivateChild { a class that the router
canActivateChild( should call first to
route: ActivatedRouteSnapshot, determine if it should

state: RouterStateSnapshot activate the child route.


Should return a boolean
):
Observable<boolean>|Promise<boolean>|boolean
{ ... }
or an
}
Observable/Promise
{ path: ..., canActivateChild:
that resolves to a
[CanActivateGuard],
boolean.

children: ... }

class ResolveGuard implements Resolve<T> { An interface for defining


a class that the router
resolve(
should call first to
route: ActivatedRouteSnapshot,
resolve route data
state: RouterStateSnapshot
before rendering the
): Observable<any>|Promise<any>|any { ...
route. Should return a
}
value or an
}
Observable/Promise
{ path: ..., resolve: [ResolveGuard] }
that resolves to a value.

class CanLoadGuard implements CanLoad { An interface for defining


a class that the router
canLoad(
should call first to check
route: Route
if the lazy loaded
):
module should be
Observable<boolean>|Promise<boolean>|boolean
loaded. Should return a
{ ... }
boolean or an
}
Observable/Promise
{ path: ..., canLoad: [CanLoadGuard],
that resolves to a
loadChildren: ... }
boolean.

You might also like