Advertisement
Guest User

Untitled

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