You are on page 1of 11

Angular Cheat Sheet Cheat Sheet

by rajanvora via cheatography.com/141179/cs/30219/

ng commands Filters (cont)

ng new app-name data | json


​ (--rou​ting) add routing Convert a JavaScript object into JSON string.
{{ json_e​xpr​ession | json : spacing}}
ng add @angul​ar/​mat​erial
e.g.
​ (install and configure the Angular Material library)
<pre id="​def​aul​t-s​pac​ing​">
ng build
{{ {'name​':'​value'} | json:4 }}
​ (build your applic​ation and places directory called "​dis​t") </p​re>
ng serve (build and serve on 4200) output:
ng serve -o (autom​ati​cally open the browser) {

ng serve -p 666 -o (use port 666) ​ ​"​nam​e": "​val​ue"


}
ng generate component csr
array | limitT​o:limit
​ or ng g c csr
Creates a new array containing only a
ng g c csr --flat (generate component without folder) ​spe​cified number of elements in an array.
ng g s csr-data (generate service objects) {{ limitT​o_e​xpr​ession | limitTo : limit :
ng g cl models/csr begin}}

​ (generates the csr class inside of the models folder) text | linky 1
Finds links in text input and turns them into html
ng g i models/csr
links.
​ (generates the csr interface inside the models folder)
* Requires ngSanitize Module
ng g p shared​/in​it-caps
<span ng-bin​d-h​tml​="li​nky​_ex​pre​ssion |
​ (generates the init-caps pipes) linky">​</s​pan>
e,g,
Filters <div ng-bin​d-h​tml​="sn​ippet | linky">
</d​iv>
<div ng-bin​d-h​tml​="sn​ipp​etW​ith​Sin​gleURL |
linky:​'_b​lan​k'">
</d​iv>
<div ng-bin​d-h​tml​="sn​ipp​etW​ith​Sin​gleURL |
linky:​'_s​elf':
{rel: 'nofol​low​'}">
</d​iv>
string | lowercase
Converts string to lowercase.
{{ lowerc​ase​_ex​pre​ssion | lowerc​ase}}
number | number [:frac​tio​nSize]
Formats a number as text.
If the input is not a number an empty string is
returned.
{{ number​_ex​pre​ssion | number : fracti​onS​ize}}
e.g.
Default format​ting:
amount | currency [:symbol]
{{ curren​cy_​exp​ression | currency : symbol :
fracti​onS​ize}}
e.g.
<span id="currency-no-fractions">
{{amount | currency:"USD$":0}}
</span>
Formats a number as a currency (ie $1,234.56).
date | date[:format]
{{ date_e​xpr​ession | date : format : timezone}}
e.g.
<span ng-non-bindable>
{{1288323623006 | date:'​MM/​dd/yyyy @ h:mma'}}
</span>
<span>
{{'1288323623006' | date:'​MM/​dd/yyyy @ h:mma'}}
</span>
output:
{{1288323623006 | date:'​MM/​dd/yyyy @ h:mma'}}:
​12/​15/​202​1@1​1:40PM
array | filter​:ex​pre​ssion
Selects a subset of items from array.
Expression takes string​​|O​b​j​ec​​t|f​​un​c​t​‐
ion()
{{ filter​_ex​pre​ssion | filter : expression :
comparator : anyPro​per​tyKey}}
e.g.
ng-rep​eat​="friend in friends | filter​:se​arc​‐
hTe​xt"

By rajanvora Published 15th December, 2021. Sponsored by Readable.com


cheatography.com/rajanvora/ Last updated 15th December, 2021. Measure your website readability!
Page 1 of 11. https://readable.com
Angular Cheat Sheet Cheat Sheet
by rajanvora via cheatography.com/141179/cs/30219/

Filters (cont) Forms (cont)

<span id='nu​mbe​r-d​efa​ult​'> user = {username: '', email: '', password: ''};


{{val | number}} constr​uctor() { }
</s​pan> ngOnIn​it(): void { }
No fractions: /**
<sp​an> * Called when the user clicks in the "​Reg​ist​er"
{{val | number:0}} * button.
</s​pan> */
Negative number: onSubmit() {
<sp​an> consol​e.l​og(​'User: ', this.u​ser.us​ern​ame);
{{-val | number:4}} consol​e.l​og(​'Email: ', this.u​ser.em​ail);
</s​pan> consol​e.l​og(​'Pa​ssword: ', this.u​ser.pa​ssw​‐
array | orderB​y:p​red​icate
[:reverse] ord);
Predicate is functi​​on​(​*​)|​​str​​in​g​|​Array. }
Reverse is boolean }
*{{ orderB​y_e​xpr​ession | orderBy : .html
expression : reverse : compar​ator}}* <di​v>
e.g. <form novalidate #regis​ter​For​m="n​gFo​rm"
ng-rep​eat​="friend in friends | orderB​y:'​-ag​‐ (ngSub​mit​)="o​nSu​bmi​t()​">
e'" <!-- User -->
string | uppercase <p>
Converts string to uppercase. <ma​t-f​orm​-fi​eld>
{{ upperc​ase​_ex​pre​ssion | upperc​ase}} <input
<h1>{{title | upperc​ase​}}<​/h1> matInput
placeh​old​er=​"​Use​rna​me"
Forms type="t​ext​"

In Angular, there are 2 types: template- [(ngMo​del​)]=​"​use​r.u​ser​nam​e"

driven(easier to use) name="u​ser​nam​e"

and reacti​ve(​rec​omm​ended for large forms) #usern​ame​="ng​Mod​el"

Templa​te-​driven: requir​ed>

Import FormsM​odule in app.mo​dule.ts <ma​t-error

Sample: *ngIf=

.ts "​use​rna​me.e​rr​ors​?.r​equ​ire​d">

import { Component, OnInit } from '@angu​‐ Username is required

lar​/core'; </m​at-​err​or>

​ ​@Co​mpo​nent({ </m​at-​for​m-f​iel​d>

​ ​ ​ ​ ​ ​ ​ ​sel​ector: 'app-n​ewu​ser', </p>

templa​teUrl: './new​use​r.c​omp​one​nt.h​tml', <!-- Email -->

styleUrls: ['./ne​wus​er.c​om​pon​ent.scss']
​ })
​ ​export class Newuse​rCo​mponent implements
OnInit {
// Data

By rajanvora Published 15th December, 2021. Sponsored by Readable.com


cheatography.com/rajanvora/ Last updated 15th December, 2021. Measure your website readability!
Page 2 of 11. https://readable.com
Angular Cheat Sheet Cheat Sheet
by rajanvora via cheatography.com/141179/cs/30219/

Forms (cont) Forms (cont)

<p> Register user


<ma​t-f​orm​-fi​eld> </b​utt​on>
<input matInput ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​</p>
placeh​old​er=​"​Ema​il" </f​orm>
type="e​mai​l" </d​iv>
[(ngMo​del​)]=​"​use​r.e​mai​l" this example uses two way binding and templa​teRef
name="e​mai​l" (for regist​erForm)
#email​="ng​Mod​el"
requir​ed> Reactive Forms:
<ma​t-error import Reacti​veF​orm​sModule in app.mo​dule.ts
*ngIf=​"​ema​il.e​rr​ors​?.r​equ​ire​d"> all the form logic and validation are done
Email is required controller
</m​at-​err​or> create a model
</m​at-​for​m-f​iel​d> .ts
</p> export class User {
<!-- Password --> ​ ​ ​use​rname: string;
<p> ​ ​ ​email: string;
<ma​t-f​orm​-fi​eld> ​ ​ ​pas​sword: string;
<input }
matInput .ts
placeh​old​er=​"​Pas​swo​rd" import { Component, OnInit } from '@angu​‐
type="p​ass​wor​d" [ lar​/core';
(ngMod​el)​]="u​ser.pa​ssw​ord​" import { User } from '../sh​are​d/u​ser';
name="p​ass​wor​d" @Compo​nent({
#passw​ord​="ng​Mod​el" ​ ​ ​sel​ector: 'app-n​ewu​ser',
requir​ed> ​ ​ ​tem​pla​teUrl: './new​use​r.c​omp​one​nt.h​‐
<ma​t-error tml',
*ngIf=​"​pas​swo​rd.e​rr​ors​?.r​equ​ire​d"> ​ ​ ​sty​leUrls: ['./ne​wus​er.c​om​pon​‐
Password is required ent.scss']
</m​at-​err​or> })
</m​at-​for​m-f​iel​d> export class Newuse​rCo​mponent implements OnInit
</p> {
<p> ​ ​ // Register form
<button type="s​ubm​it" ​ ​ ​reg​ist​erForm: FormGroup;
mat-button ​ ​ ​ ​ // form for submitting the new user
[disab​led​]="r​egi​ste​rFo​rm.f​or​m.i​nva​lid​"> ​ ​ ​myUser: User;
​ ​ ​ ​ // the user generated from the form
​ ​ ​@Vi​ewC​hil​d('​new​use​rForm') userFo​rmD​‐
ire​ctive:
​ ​ ​ ​ ​ ​For​mGr​oup​Dir​ective;
​ ​ // reference to the form in the HTML
template,
​ ​ // in order to perform validation
​ ​ /*

By rajanvora Published 15th December, 2021. Sponsored by Readable.com


cheatography.com/rajanvora/ Last updated 15th December, 2021. Measure your website readability!
Page 3 of 11. https://readable.com
Angular Cheat Sheet Cheat Sheet
by rajanvora via cheatography.com/141179/cs/30219/

Forms (cont) Forms (cont)

​ ​ ​ * The errors being shown for each field. ​ ​ }


​ ​ ​ * The form will automa​tically update with };
​ ​ ​ ​ * the errors stored here. ​ ​ ​
​ ​ ​ */ /**
​ ​ ​ ​for​mErrors = { * Inject a FormBu​ilder for creating a FormGroup.
​ ​ ​ ​ ​ ​ ​'us​ern​ame': '', */
'email': '', constr​uct​or(​private fb: FormBu​ilder) {
'passw​ord': '' ​ ​thi​s.c​rea​teF​orm();
​ ​ ​ } }
​ ​ /* ​ ​ ​
​ ​ ​ ​ * Messages that will be shown in the /**
​ ​ ​ ​ * mat-error elements for each type of * Create the comment form with the injected
validation error. FormBu​ilder.
​ ​ ​ ​ */ */
​ ​ ​ ​val​ida​tio​nMe​ssages = { create​Form(){
'usern​ame': { ​ ​ ​thi​s.r​egi​ste​rForm = this.f​b.g​roup({
'requi​red': ​ ​ ​use​rname: ['',
'Username is requir​ed.', ​ ​ ​ ​ ​ ​[Va​lid​ato​rs.r​eq​uired,
​ ​ ​ ​ ​ ​ ​ ​'mi​nle​ngth': ​ ​ ​ ​ ​ ​ ​Val​ida​tor​s.m​inL​eng​th(3),
'Username must be at ​ ​ ​ ​ ​ ​ ​Val​ida​tor​s.m​axL​eng​th(20)] ],
least 3 characters long.', ​ ​ ​pas​sword: ['',
'maxle​ngth': ​ ​ ​ ​ ​[Va​lid​ato​rs.r​eq​uired,
'Username cannot be ​ ​ ​ ​ ​ ​Val​ida​tor​s.m​inL​eng​th(8)] ],
more than 20 characters long.' ​ ​ ​email: ['',
​ ​ }, ​ ​ ​ ​[Va​lid​ato​rs.r​eq​uired,
​ ​ ​'pa​ssw​ord': { ​ ​ ​ ​ ​Val​ida​tor​s.e​mail] ],
'requi​red': });
'Password is requir​ed.', this.r​egi​ste​rFo​rm.v​al​ueC​han​ges.su​bsc​ribe(
'minle​ngth': ​ ​ data => this.o​nVa​lue​Cha​nge​d());
'Password must be at // every time a value changes inside the form, the
least 8 characters long.' // onValu​eCh​anged() method will be triggered
​ ​ }, this.o​nVa​lue​Cha​nged();
​ ​ ​'em​ail': { // reset validation messages
'requi​red': }
'Email is requir​ed.', /**
'email': * Validate the form after a value change.
'Email not in valid format.' */
onValu​eCh​anged() {
​ ​ ​if(​!th​is.r​eg​ist​erForm) { return; }

By rajanvora Published 15th December, 2021. Sponsored by Readable.com


cheatography.com/rajanvora/ Last updated 15th December, 2021. Measure your website readability!
Page 4 of 11. https://readable.com
Angular Cheat Sheet Cheat Sheet
by rajanvora via cheatography.com/141179/cs/30219/

Forms (cont) Forms (cont)

​ ​ // in case the form hasn't been created yet this.m​yUser = this.r​egi​ste​rFo​rm.v​alue;


​ ​ ​const form = this.r​egi​ste​rForm; ​ // TODO: send the form data to somewhere else
​ ​ ​ ​ ​ // the form values are constantly ​ // Reset the form
changing, ​ ​ ​ ​ ​ ​ ​ ​thi​s.r​egi​ste​rFo​rm.r​eset({
​ ​ ​ ​ // that's why we have to take a snapshot username: '',
// Validate the form email: '',
​ ​ for (const field in this.f​orm​Errors) { password: ''
​ ​ ​ ​ // Iterate the form field by field });
​ ​ ​ ​ if (this.f​or​mEr​ror​s.h​asO​wnP​rop​‐ this.u​ser​For​mDi​rec​tiv​e.r​ese​tFo​rm();
ert​y(f​ield)) { }
this.f​orm​Err​ors​[field] = ''; }
// clear previous error message (if any) .html
const control = form.g​et(​field); <di​v>
if (control && contro​l.dirty ​ ​<form
&& !contr​ol.v​alid) { ​ ​ ​ ​nov​alidate
// If this form field has been ​ ​ ​ ​[fo​rmG​rou​p]=​"​reg​ist​erF​orm​"
// touched an it's not valid ​ ​ ​ ​#ne​wus​erF​orm​="ng​For​m"
const messages = ​ ​ ​ ​(ng​Sub​mit​)="o​nSu​bmi​t()​">
this.v​ali​dat​ion​Mes​sag​es[​field]; ​ ​ ​ ​<p>
for (const key in contro​l.e​rrors) { <ma​t-f​orm​-fi​eld>
if (contr​ol.e​rr​ors.ha​sOw​nPr​ope​rty​(key)) { <input
// Add the corres​ponding error messages matInput
// to the array of form errors. formCo​ntr​olN​ame​="us​ern​ame​"
// The form mat-error elements will update placeh​old​er=​"​Use​rna​me"
// immediatly with the new form errors. type="t​ext​"
this.f​orm​Err​ors​[field] += requir​ed>
messag​es[key] + ' '; <ma​t-error
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ } *ngIf=​"​for​mEr​ror​s.u​ser​nam​e">
} {{formErrors.username}}
​ ​ } </m​at-​err​or>
​ ​ ​ ​ ​ ​ } </m​at-​for​m-f​iel​d>
​ ​ ​ } </p>
} <p>
/** <ma​t-f​orm​-fi​eld>
* Called when the user clicks the "​Sub​mit​" <input
button in the form matInput
*/
onSubm​it(){
​ // Create a User object from the form data

By rajanvora Published 15th December, 2021. Sponsored by Readable.com


cheatography.com/rajanvora/ Last updated 15th December, 2021. Measure your website readability!
Page 5 of 11. https://readable.com
Angular Cheat Sheet Cheat Sheet
by rajanvora via cheatography.com/141179/cs/30219/

Forms (cont) Directives

formCo​ntr​olN​ame​="pa​ssw​ord​" ng-app="plaintext"
placeh​old​er=​"​Pas​swo​rd" ng-bin​d[-​htm​l-u​nsafe]=
"​exp​res​sio​n"
type="p​ass​wor​d" ng-bin​d-t​emp​‐
requir​ed> late="string{{expression}}string{{expression}}"
<ma​t-error ng-change="​exp​res​sio​n"
*ngIf=​"​for​mEr​ror​s.p​ass​wor​d"> ng-che​cked=
"​boo​lea​n"
{{formErrors.password}} ng-cla​ss[​-ev​en|​-odd]=
"​str​ing​|ob​jec​t"
</m​at-​err​or> ng-[db​l]c​lick=
"​exp​res​sio​n"
</m​at-​for​m-f​iel​d> ng-cloak="​boo​lea​n"
</p> ng-con​tro​ller=
"​pla​int​ext​"
<p> ng-dis​abled=
"​boo​lea​n"
<ma​t-f​orm​-fi​eld> <fo​rm|​ng-form
name="p​lai​nte​xt"> ng-form="​‐
|
<input pla​int​ext​"
matInput ng-hid​e|show=
"​boo​lea​n"
formCo​ntr​olN​ame​="em​ail​" ng-href="plaintext{{string}}"
placeh​old​er=​"​Ema​il" ng-inc​lude=
"​str​ing​"|
<ng​-in​clude
src="st​‐
type="e​mai​l" rin​g"
requir​ed> onload="expression" autosc​rol​l="e​xpr​ess​‐
<ma​t-error ion​">
*ngIf=​"​for​mEr​ror​s.e​mai​l"> ng-init="​exp​res​sio​n"
{{formErrors.email}} <input ng-pat​tern=
"​/r​​ege​​x/​"
</m​at-​err​or> ng-min​​length ng-max​​length ng-req​​uired
​ ​ ​ ​ ​ ​ ​</m​at-​for​m-f​iel​d> <input ng-list="​del​imi​ter​|re​gex​">
​ ​ ​</p> <input type="c​​he​c​k​bo​​x"
ng-tru​​e-​value=
"​‐
​ ​<button type="s​ubm​it" pl​​ain​​te​x​t​"
​ ​ ​ ​[di​sab​led​]="r​egi​ste​rFo​rm.i​nv​ali​d" ng-fal​​se​-​v​alue=
"​pl​​ain​​te​x​t​">
​ ​ ​ ​mat​-ra​ise​d-b​utton ng-model="​exp​res​sio​n"
​ ​ ​ ​col​or=​"​pri​mar​y"> ng-mou​sedown=
"​exp​res​sio​n"
Submit ng-mou​see​nter=
"​exp​res​sio​n"
​ ​</b​utt​on> ng-mou​sel​eave=
"​exp​res​sio​n"
​ ​</f​orm> ng-mou​semove=
"​exp​res​sio​n"
</d​iv> ng-mou​seover=
"​exp​res​sio​n"
ng-mou​seup=
"​exp​res​sio​n"
<select ng-mul​​tiple
>
ng-non​-bi​ndable
ng-opt​ions=
"​select [as label] [group by group]
for ([key,] value) in object​|ar​ray​"
ng-plu​ral​ize​|<n​g-p​lur​alize
count=​"​num​‐
ber​"
when="object" offset​="nu​mbe​r">
ng-rea​donly=
"​exp​res​sio​n"
ng-repeat="​([key,] value) in object​|ar​ray​"
<option ng-sel​ected=
"​boo​lea​n">
ng-src="​str​ing​"

By rajanvora Published 15th December, 2021. Sponsored by Readable.com


cheatography.com/rajanvora/ Last updated 15th December, 2021. Measure your website readability!
Page 6 of 11. https://readable.com
Angular Cheat Sheet Cheat Sheet
by rajanvora via cheatography.com/141179/cs/30219/

Directives (cont) Templa​te-​Ref​erence Variables

ng-style="​str​ing​|ob​jec​t" Inside the template of a component, we can assign


ng-submit="​exp​res​sio​n" a
ng-switch="​exp​res​sio​n"|<
ng-switch on="​exp​‐ ​ref​erence to an HTML element so we can access
res​sio​n"> its content
ng-swi​​tc​h​-​when=
"​pl​​ain​​te​x​t​" from other elements inside the DOM.
ng-swi​​tc​h​-​de​​fault
ng-vie​w|<​ng-​vie​w> RxJS
ng-bin​d-html=
"​exp​res​sio​n" A library for reactive programming in JS, an
​asy​nch​ron​ous​-pr​ogr​amming paradigm where it
Routing exists an
With routing, you can introduce navigation between ​entity called Observ​abl​e<T​>, which consists
screens in a value
(actually, between Angular compon​ents) in your of type T that changes over time.
app. Our applic​ation components can subscribe to this
Define routes in app-ro​uti​ng.m​od​ule.ts observ​able,
Instan​tiate the router in html as : ​bec​oming observers by implem​enting a callback
​ <ro​ute​r-o​utl​et>​</r​out​er-​out​let> which will be
To redirect the user to a defined route ​tri​ggered whenever the value changes.
use the routerLink directive The main method of observable objects is
​sub​scr​ibe​(data => {}), which enables us to
Data Binding ask Angular to

Angular components are defined in three files: ​notify us whenever the data changes.

an HTML file for the layout (view), Other intere​sting functions: map, pipe, filter,

a TypeScript file for the logic (contr​oller), and delay..

a CSS file for the style.


One-way data binding is the mechanism for rendering Services

in the Components without UI


view objects defined in the controller (property ng g s servic​es/​dat​afetch
binding) Tell Angular to inject this service in all of the
and for allowing the view to call methods in the app components that ask for it, so let’s add it
​con​troller (event binding). to
Two-way data binding, where using the notation the providers section of the app.mo​dule.tsfile
[(obje​ct)], To use it in any component of our app,
a bidire​ctional relati​onship between the view you just have to ask for it in the constr​uctor.
and
the controller is establ​ished, so any changes on Promises
the bound
​object from the controller will be reproduced in
the
view and vice versa.

Structural Directives
Structural directives allow the developers to These are JS mechanism for async programming,
include where a
some code logic inside the HTML template in a very ​pending value is returned, which might be
quick available soon
and easy way in order to determine when and how ​(re​solve) or never (reject)
many Promises allow you to specify what to do when the
​times an HTML element has to be rendered answer to
your request arrives or when something goes
wrong, and
​mea​nwhile you can continue with the execution of
your program.
.servi​ce.ts
@Injec​table({
​ ​ ​pro​vid​edIn: 'root'
})
export class UserSe​rvice {

By rajanvora Published 15th December, 2021. Sponsored by Readable.com


cheatography.com/rajanvora/ Last updated 15th December, 2021. Measure your website readability!
Page 7 of 11. https://readable.com
Angular Cheat Sheet Cheat Sheet
by rajanvora via cheatography.com/141179/cs/30219/

Promises (cont) HTTP Request

​ ​ ​con​str​uctor() {} The HttpClient class underlies the JavaScript


​ ​ ​get​Use​rs(): Promis​e<U​ser> { XMLHttpRequest
​ ​ ​ ​ ​ ​return new Promise( ​object and returns an observable with the
​ ​ ​ ​ ​ ​ ​ ​ ​ ​fun​cti​on(​res​olve, reject){ server​-re​sponse
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ // get the data from body encoded as an object of the specified class.
some API... Sample:
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​if(​suc​ces​sful) { Image a GET request to http:/​/lo​cal​hos​t:1​‐
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ // Data was 234​/items
succes​sfully retrieved ​returns following JSON
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​res​olv​e(r​‐ [
esult); {
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ } else { "​nam​e": "​Por​celain cup",
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ // There was an "​pri​ce": 9.99,
error retrieving the data "​qua​nti​ty": 20
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​rej​ect​(er​‐ },
ror); {
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ } "​nam​e": "​Photo frame",
}); "​pri​ce": 5.99,
​ ​ ​ } "​qua​nti​ty": 50
} }
.ts (component that consumes the service) ]
@Compo​nent({ create a model to capture the data
​ ​ ​sel​ector: 'app-u​sers', export class Item {
​ ​ ​tem​pla​teUrl: './use​rs.c​om​pon​ent.html', name: string;
​ ​ ​sty​leUrls: ['./us​ers.co​mpo​nen​t.s​css'] price: number;
}) quantity: number;
export class UsersC​omp​onent implements OnInit { }
​ ​ ​con​str​uct​or(​private userSe​rvice: After importing HttpCl​ien​tModule in app.mo​‐
UserSe​rvice) {} dule.ts
​ ​ ​myU​sers: User[]; .servi​ce.ts
​ ​ ​get​Use​rs(){ import { Inject​able, Inject } from '@angu​‐
this.u​ser​Ser​vic​e.g​etU​sers() lar​/core';
.then(​users => this.m​yUsers = users) import { Item } from '../sh​are​d/item'
​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ // the Promise import { Observable } from 'rxjs';
was resolved import { map, catchError } from 'rxjs/​ope​rat​‐
.catch​(error => consol​e.l​og(​error)) ors';
// the Promise was rejected import { HttpClient } from '@angu​lar​/co​mmo​‐
} n/h​ttp';
​ ​ ​ngO​nIn​it(): void {} @Injec​table({
} provid​edIn: 'root'
})
export class ItemSe​rvice {
baseURL = 'http:​//l​oca​lho​st:​1234/'

By rajanvora Published 15th December, 2021. Sponsored by Readable.com


cheatography.com/rajanvora/ Last updated 15th December, 2021. Measure your website readability!
Page 8 of 11. https://readable.com
Angular Cheat Sheet Cheat Sheet
by rajanvora via cheatography.com/141179/cs/30219/

HTTP Request (cont) HTTP Request (cont)

/** export class ItemsC​omp​onent implements OnInit {


* Injects an HTTPClient and the BaseURL constr​uct​or(​private itemSe​rvice: ItemSe​rvice)
* into the service. {}
* @param http HTTPClient used for making myItems: Item[];
* HTTP requests to the backend. ngOnIn​it(): void {
*/ this.i​tem​Ser​vic​e.g​etI​tems()
constr​uct​or(​private http: HttpCl​ient) { } .subsc​rib​e(items => this.m​yItems = items,
/** // any time the value of the Observable
* Return the list of items from the API, // changes, update the myItems object
* as an array of Item objects error => consol​e.l​og(​err​or));
*/ // if there is an error, log it to the
getIte​ms(): Observ​abl​e<I​tem​[]> { // console
return this.h​ttp.ge​t<I​tem​[]> }
(this.b​aseURL + 'items'); }
// make the HTTP GET request
} Workflow
/** Steps to creating a reactive form:
* Send a new item to the API, as 1. Create the Domain Model
* an Item object 2. Create the Controller with references to View
*/ 3. Create the View
addIte​m(item: Item): Observ​abl​e<I​tem> { 4. Add Valida​​tions
return this.h​ttp.po​st<​Ite​m> 5. Add Submit Validation Control
(this.b​aseURL + 'items', item); 6. Add Dynamic Behaviors
// make the HTTP POST request
}
}
component to consume the service:
.ts
import { Component, OnInit } from '@angu​‐
lar​/core';
import { ItemSe​rvice } from '../se​rvi​‐
ces​/item';
import { Item } from '../sh​are​d/i​tem';
@Compo​nent({
selector: 'app-i​tems',
templa​teUrl: './ite​ms.c​om​pon​ent.html',
styleUrls: ['./it​ems.co​mpo​nen​t.s​css']
})

By rajanvora Published 15th December, 2021. Sponsored by Readable.com


cheatography.com/rajanvora/ Last updated 15th December, 2021. Measure your website readability!
Page 9 of 11. https://readable.com

You might also like