angular/aio/content/guide/cheatsheet.md

124 lines
43 KiB
Markdown
Raw Normal View History

<div class="center-layout-wide">
<h1 class="no-toc">Cheat Sheet</h1>
| Bootstrapping | Details |
|:--- |:--- |
| <code-example format="typescript" hideCopy language="typescript"> import { platformBrowserDynamic } from '&commat;angular/platform-browser-dynamic'; </code-example> | Import `platformBrowserDynamic` from `@angular/platform-browser-dynamic`. |
| <code-example format="typescript" hideCopy language="typescript"> platformBrowserDynamic().bootstrapModule(AppModule); </code-example> | Bootstraps the application, using the root component from the specified `NgModule`. |
| NgModules | Details |
|:--- |:--- |
| <code-example format="typescript" hideCopy language="typescript"> import { NgModule } from '&commat;angular/core'; </code-example> | Import `NgModule` from `@angular/core`. |
| <code-example format="typescript" hideCopy language="typescript"> &commat;NgModule({ &NewLine;&nbsp; declarations: &hellip;, &NewLine;&nbsp; imports: &hellip;, &NewLine;&nbsp; exports: &hellip;, &NewLine;&nbsp; providers: &hellip;, &NewLine;&nbsp; bootstrap: &hellip; &NewLine;}) &NewLine;class MyModule {} </code-example> | Defines a module that contains components, directives, pipes, and providers. |
| <code-example format="typescript" hideCopy language="typescript"> declarations: [ &NewLine;&nbsp; MyRedComponent, &NewLine;&nbsp; MyBlueComponent, &NewLine;&nbsp; MyDatePipe &NewLine;] </code-example> | List of components, directives, and pipes that belong to this module. |
| <code-example format="typescript" hideCopy language="typescript"> imports: [ &NewLine;&nbsp; BrowserModule, &NewLine;&nbsp; SomeOtherModule &NewLine;] </code-example> | List of modules to import into this module. Everything from the imported modules is available to `declarations` of this module. |
| <code-example format="typescript" hideCopy language="typescript"> exports: [ &NewLine;&nbsp; MyRedComponent, &NewLine;&nbsp; MyDatePipe &NewLine;] </code-example> | List of components, directives, and pipes visible to modules that import this module. |
| <code-example format="typescript" hideCopy language="typescript"> providers: [ &NewLine;&nbsp; MyService, &NewLine;&nbsp; { provide: &hellip; } &NewLine;] </code-example> | List of dependency injection providers visible both to the contents of this module and to importers of this module. |
| <code-example format="typescript" hideCopy language="typescript"> bootstrap: [MyAppComponent] </code-example> | List of components to bootstrap when this module is bootstrapped. |
| Template syntax | Details |
|:--- |:--- |
| <code-example format="html" hideCopy language="html"> &lt;input [value]="firstName"&gt; </code-example> | Binds property `value` to the result of expression `firstName`. |
| <code-example format="html" hideCopy language="html"> &lt;div [attr.role]="myAriaRole"&gt; </code-example> | Binds attribute `role` to the result of expression `myAriaRole`. |
| <code-example format="html" hideCopy language="html"> &lt;div [class.extra-sparkle]="isDelightful"&gt; </code-example> | Binds the presence of the CSS class `extra-sparkle` on the element to the truthiness of the expression `isDelightful`. |
| <code-example format="html" hideCopy language="html"> &lt;div [style.width.px]="mySize"&gt; </code-example> | Binds style property `width` to the result of expression `mySize` in pixels. Units are optional. |
| <code-example format="html" hideCopy language="html"> &lt;button (click)="readRainbow(&dollar;event)"&gt; </code-example> | Calls method `readRainbow` when a click event is triggered on this button element \(or its children\) and passes in the event object. |
| <code-example format="html" hideCopy language="html"> &lt;div title="Hello {{ponyName}}"&gt; </code-example> | Binds a property to an interpolated string, for example, "Hello Seabiscuit". Equivalent to: <code-example format="html" hideCopy language="html"> &lt;div [title]="'Hello ' + ponyName"&gt; </code-example> |
| <code-example format="html" hideCopy language="html"> &lt;p&gt; &NewLine;&nbsp; Hello {{ponyName}} &NewLine;&lt;/p&gt; </code-example> | Binds text content to an interpolated string, for example, "Hello Seabiscuit". |
| <code-example format="html" hideCopy language="html"> &lt;my-cmp [(title)]="name"&gt; </code-example> | Sets up two-way data binding. Equivalent to: <code-example format="html" hideCopy language="html"> &lt;my-cmp [title]="name" (titleChange)="name=&dollar;event"&gt; </code-example> |
| <code-example format="html" hideCopy language="html"> &lt;video &num;movieplayer &hellip;&gt;&lt;/video&gt; &NewLine;&lt;button (click)="movieplayer.play()"&gt; &NewLine;&nbsp; Play &NewLine;&lt;/button&gt; </code-example> | Creates a local variable `movieplayer` that provides access to the `video` element instance in data-binding and event-binding expressions in the current template. |
| <code-example format="html" hideCopy language="html"> &lt;p &ast;myUnless="myExpression"&gt; &NewLine;&nbsp; &hellip; &NewLine;&lt;/p&gt; </code-example> | The asterisk \(`*`\) character turns the current element into an embedded template. Equivalent to: <code-example format="html" hideCopy language="html"> &lt;ng-template [myUnless]="myExpression"&gt; &NewLine;&nbsp; &lt;p&gt; &NewLine;&nbsp;&nbsp;&nbsp; &hellip; &NewLine;&nbsp; &lt;/p&gt; &NewLine;&lt;/ng-template&gt; </code-example> |
| <code-example format="html" hideCopy language="html"> &lt;p&gt; &NewLine;&nbsp; Card No.: {{cardNumber &verbar; myCardNumberFormatter}} &NewLine;&lt;/p&gt; </code-example> | Transforms the current value of expression `cardNumber` using the pipe called `myCardNumberFormatter`. |
| <code-example format="html" hideCopy language="html"> &lt;p&gt; &NewLine;&nbsp; Employer: {{employer?.companyName}} &NewLine;&lt;/p&gt; </code-example> | The safe navigation operator \(`?`\) means that the `employer` field is optional and if `undefined`, the rest of the expression should be ignored. |
| <code-example format="html" hideCopy language="html"> &lt;svg:rect x="0" &NewLine;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; y="0" &NewLine;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; width="100" &NewLine;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; height="100"/&gt; </code-example> | An SVG snippet template needs an `svg:` prefix on its root element to disambiguate the SVG element from an HTML component. |
| <code-example format="html" hideCopy language="html"> &lt;svg&gt; &NewLine;&nbsp; &lt;rect x="0" &NewLine;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; y="0" &NewLine;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; width="100" &NewLine;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; height="100"/&gt; &NewLine;&lt;/svg&gt; </code-example> | An `<svg>` root element is detected as an SVG element automatically, without the prefix. |
| Built-in directives | Details |
|:--- |:--- |
| <code-example format="typescript" hideCopy language="typescript"> import { CommonModule } from '&commat;angular/common'; </code-example> | Import `CommonModule` from `@angular/common`. |
| <code-example format="html" hideCopy language="html"> &lt;section &ast;ngIf="showSection"&gt; </code-example> | Removes or recreates a portion of the DOM tree based on the `showSection` expression. |
| <code-example format="html" hideCopy language="html"> &lt;li &ast;ngFor="let item of list"&gt; </code-example> | Turns the `li` element and its contents into a template, and uses that to instantiate a view for each item in list. |
| <code-example format="html" hideCopy language="html"> &lt;div [ngSwitch]="conditionExpression"&gt;&NewLine;&nbsp; &lt;ng-template [ngSwitchCase]="case1Exp"&gt; &NewLine;&nbsp;&nbsp;&nbsp; &hellip; &NewLine;&nbsp; &lt;/ng-template&gt;&NewLine;&nbsp; &lt;ng-template ngSwitchCase="case2LiteralString"&gt; &NewLine;&nbsp;&nbsp;&nbsp; &hellip; &NewLine;&nbsp; &lt;/ng-template&gt;&NewLine;&nbsp; &lt;ng-template ngSwitchDefault&gt; &NewLine;&nbsp;&nbsp;&nbsp; &hellip; &NewLine;&nbsp; &lt;/ng-template&gt; &NewLine;&lt;/div&gt; </code-example> | Conditionally swaps the contents of the `div` by selecting one of the embedded templates based on the current value of `conditionExpression`. |
| <code-example format="html" hideCopy language="html"> &lt;div [ngClass]="{'active': isActive, &NewLine;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 'disabled': isDisabled}"&gt; </code-example> | Binds the presence of CSS classes on the element to the truthiness of the associated map values. The right-hand expression should return `{class-name: true/false}` map. |
| <code-example format="html" hideCopy language="html"> &lt;div [ngStyle]="{'property': 'value'}"&gt; &NewLine;&lt;div [ngStyle]="dynamicStyles()"&gt; </code-example> | Allows you to assign styles to an HTML element using CSS. You can use CSS directly, as in the first example, or you can call a method from the component. |
| Forms | Details |
|:--- |:--- |
| <code-example format="typescript" hideCopy language="typescript"> import { FormsModule } from '&commat;angular/forms'; </code-example> | Import `FormsModule` from `@angular/forms`. |
| <code-example format="html" hideCopy language="html"> &lt;input [(ngModel)]="userName"&gt; </code-example> | Provides two-way data-binding, parsing, and validation for form controls. |
| Class decorators | Details |
|:--- |:--- |
| <code-example format="typescript" hideCopy language="typescript"> import { Directive, &hellip; } from '&commat;angular/core'; </code-example> | Import `Directive, &hellip;` from `@angular/core';`. |
| <code-example format="typescript" hideCopy language="typescript"> &commat;Component({&hellip;}) &NewLine;class MyComponent() {} </code-example> | Declares that a class is a component and provides metadata about the component. |
| <code-example format="typescript" hideCopy language="typescript"> &commat;Directive({&hellip;}) &NewLine;class MyDirective() {} </code-example> | Declares that a class is a directive and provides metadata about the directive. |
| <code-example format="typescript" hideCopy language="typescript"> &commat;Pipe({&hellip;}) &NewLine;class MyPipe() {} </code-example> | Declares that a class is a pipe and provides metadata about the pipe. |
| <code-example format="typescript" hideCopy language="typescript"> &commat;Injectable() &NewLine;class MyService() {} </code-example> | Declares that a class can be provided and injected by other classes. Without this decorator, the compiler won't generate enough metadata to allow the class to be created properly when it's injected somewhere. |
| Directive configuration | Details |
|:--- |:--- |
| <code-example format="typescript" hideCopy language="typescript"> &commat;Directive({ &NewLine;&nbsp; property1: value1, &NewLine;&nbsp; &hellip; &NewLine;}) </code-example> | Add `property1` property with `value1` value to Directive. |
| <code-example format="typescript" hideCopy language="typescript"> selector: '.cool-button:not(a)' </code-example> | Specifies a CSS selector that identifies this directive within a template. Supported selectors include `element`, `[attribute]`, `.class`, and `:not()`. <br /> Does not support parent-child relationship selectors. |
| <code-example format="typescript" hideCopy language="typescript"> providers: [ &NewLine;&nbsp; MyService, &NewLine;&nbsp; { provide: &hellip; } &NewLine;] </code-example> | List of dependency injection providers for this directive and its children. |
| Component configuration <br /> `@Component` extends `@Directive`, so the `@Directive` configuration applies to components as well | Details |
|:--- |:--- |
| <code-example format="typescript" hideCopy language="typescript"> viewProviders: [MyService, { provide: &hellip; }] </code-example> | List of dependency injection providers scoped to this component's view. |
| <code-example format="typescript" hideCopy language="typescript"> template: 'Hello {{name}}' &NewLine;templateUrl: 'my-component.html' </code-example> | Inline template or external template URL of the component's view. |
| <code-example format="typescript" hideCopy language="typescript"> styles: ['.primary {color: red}'] &NewLine;styleUrls: ['my-component.css'] </code-example> | List of inline CSS styles or external stylesheet URLs for styling the component's view. |
| Class field decorators for directives and components | Details |
|:--- |:--- |
| <code-example format="typescript" hideCopy language="typescript"> import { Input, &hellip; } from '&commat;angular/core'; </code-example> | Import `Input, ...` from `@angular/core`. |
| <code-example format="typescript" hideCopy language="typescript"> &commat;Input() myProperty; </code-example> | Declares an input property that you can update using property binding \(example: `<my-cmp [myProperty]="someExpression">`\). |
| <code-example format="typescript" hideCopy language="typescript"> &commat;Output() myEvent = new EventEmitter(); </code-example> | Declares an output property that fires events that you can subscribe to with an event binding \(example: `<my-cmp (myEvent)="doSomething()">`\). |
| <code-example format="typescript" hideCopy language="typescript"> &commat;HostBinding('class.valid') isValid; </code-example> | Binds a host element property \(here, the CSS class `valid`\) to a directive/component property \(`isValid`\). |
| <code-example format="typescript" hideCopy language="typescript"> &commat;HostListener('click', ['&dollar;event']) onClick(e) {&hellip;} </code-example> | Subscribes to a host element event \(`click`\) with a directive/component method \(`onClick`\), optionally passing an argument \(`$event`\). |
| <code-example format="typescript" hideCopy language="typescript"> &commat;ContentChild(myPredicate) myChildComponent; </code-example> | Binds the first result of the component content query \(`myPredicate`\) to a property \(`myChildComponent`\) of the class. |
| <code-example format="typescript" hideCopy language="typescript"> &commat;ContentChildren(myPredicate) myChildComponents; </code-example> | Binds the results of the component content query \(`myPredicate`\) to a property \(`myChildComponents`\) of the class. |
| <code-example format="typescript" hideCopy language="typescript"> &commat;ViewChild(myPredicate) myChildComponent; </code-example> | Binds the first result of the component view query \(`myPredicate`\) to a property \(`myChildComponent`\) of the class. Not available for directives. |
| <code-example format="typescript" hideCopy language="typescript"> &commat;ViewChildren(myPredicate) myChildComponents; </code-example> | Binds the results of the component view query \(`myPredicate`\) to a property \(`myChildComponents`\) of the class. Not available for directives. |
| Directive and component change detection and lifecycle hooks \(implemented as class methods\) | Details |
|:--- |:--- |
| <code-example format="typescript" hideCopy language="typescript"> constructor(myService: MyService, &hellip;) { &hellip; } </code-example> | Called before any other lifecycle hook. Use it to inject dependencies, but avoid any serious work here. |
| <code-example format="typescript" hideCopy language="typescript"> ngOnChanges(changeRecord) { &hellip; } </code-example> | Called after every change to input properties and before processing content or child views. |
| <code-example format="typescript" hideCopy language="typescript"> ngOnInit() { &hellip; } </code-example> | Called after the constructor, initializing input properties, and the first call to `ngOnChanges`. |
| <code-example format="typescript" hideCopy language="typescript"> ngDoCheck() { &hellip; } </code-example> | 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. |
| <code-example format="typescript" hideCopy language="typescript"> ngAfterContentInit() { &hellip; } </code-example> | Called after `ngOnInit` when the component's or directive's content has been initialized. |
| <code-example format="typescript" hideCopy language="typescript"> ngAfterContentChecked() { &hellip; } </code-example> | Called after every check of the component's or directive's content. |
| <code-example format="typescript" hideCopy language="typescript"> ngAfterViewInit() { &hellip; } </code-example> | Called after `ngAfterContentInit` when the component's views and child views / the view that a directive is in has been initialized. |
| <code-example format="typescript" hideCopy language="typescript"> ngAfterViewChecked() { &hellip; } </code-example> | Called after every check of the component's views and child views / the view that a directive is in. |
| <code-example format="typescript" hideCopy language="typescript"> ngOnDestroy() { &hellip; } </code-example> | Called once, before the instance is destroyed. |
| Dependency injection configuration | Details |
|:--- |:--- |
| <code-example format="typescript" hideCopy language="typescript"> { provide: MyService, useClass: MyMockService } </code-example> | Sets or overrides the provider for `MyService` to the `MyMockService` class. |
| <code-example format="typescript" hideCopy language="typescript"> { provide: MyService, useFactory: myFactory } </code-example> | Sets or overrides the provider for `MyService` to the `myFactory` factory function. |
| <code-example format="typescript" hideCopy language="typescript"> { provide: MyValue, useValue: 41 } </code-example> | Sets or overrides the provider for `MyValue` to the value `41`. |
| Routing and navigation | Details |
|:--- |:--- |
| <code-example format="typescript" hideCopy language="typescript"> import { Routes, RouterModule, &hellip; } from '&commat;angular/router'; </code-example> | Import `Routes, RouterModule, ...` from `@angular/router`. |
| <code-example format="typescript" hideCopy language="typescript"> const routes: Routes = [ &NewLine;&nbsp; { path: '', component: HomeComponent }, &NewLine;&nbsp; { path: 'path/:routeParam', component: MyComponent }, &NewLine;&nbsp; { path: 'staticPath', component: &hellip; }, &NewLine;&nbsp; { path: '**', component: &hellip; }, &NewLine;&nbsp; { path: 'oldPath', redirectTo: '/staticPath' }, &NewLine;&nbsp; { path: &hellip;, component: &hellip;, data: { message: 'Custom' } } &NewLine;]); &NewLine; &NewLine;const routing = RouterModule.forRoot(routes); </code-example> | Configures routes for the application. Supports static, parameterized, redirect, and wildcard routes. Also supports custom route data and resolve. |
| <code-example format="html" hideCopy language="html"> &lt;router-outlet&gt;&lt;/router-outlet&gt; &NewLine;&lt;router-outlet name="aux"&gt;&lt;/router-outlet&gt; </code-example> | Marks the location to load the component of the active route. |
| <code-example format="html" hideCopy language="html"> &lt;a routerLink="/path"&gt; &NewLine;&lt;a [routerLink]="[ '/path', routeParam ]"&gt; &NewLine;&lt;a [routerLink]="[ '/path', { matrixParam: 'value' } ]"&gt; &NewLine;&lt;a [routerLink]="[ '/path' ]" [queryParams]="{ page: 1 }"&gt; &NewLine;&lt;a [routerLink]="[ '/path' ]" fragment="anchor"&gt; </code-example> | 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. |
| <code-example format="html" hideCopy language="html"> &lt;a [routerLink]="[ '/path' ]" routerLinkActive="active"&gt; </code-example> | The provided classes are added to the element when the `routerLink` becomes the current active route. |
| <code-example format="html" hideCopy language="html"> &lt;a [routerLink]="[ '/path' ]" routerLinkActive="active" ariaCurrentWhenActive="page"&gt; </code-example> | The provided classes and `aria-current` attribute are added to the element when the `routerLink` becomes the current active route. |
| <code-example format="typescript" hideCopy language="typescript"> function canActivateGuard: CanActivateFn = &NewLine;&nbsp; ( &NewLine;&nbsp;&nbsp;&nbsp; route: ActivatedRouteSnapshot, &NewLine;&nbsp;&nbsp;&nbsp; state: RouterStateSnapshot &NewLine;&nbsp; ) => { &hellip; } &NewLine; &NewLine;{ path: &hellip;, canActivate: [canActivateGuard] } </code-example> | An interface for defining a function that the router should call first to determine if it should activate this component. Should return a <code>boolean&verbar;UrlTree</code> or an Observable/Promise that resolves to a <code>boolean&verbar;UrlTree</code>. |
| <code-example format="typescript" hideCopy language="typescript"> function canDeactivateGuard: CanDeactivateFn&lt;T&gt; = &NewLine;&nbsp; ( &NewLine;&nbsp;&nbsp;&nbsp; component: T, &NewLine;&nbsp;&nbsp;&nbsp; route: ActivatedRouteSnapshot, &NewLine;&nbsp;&nbsp;&nbsp; state: RouterStateSnapshot &NewLine;&nbsp; ) => { &hellip; } &NewLine; &NewLine;{ path: &hellip;, canDeactivate: [canDeactivateGuard] } </code-example> | An interface for defining a function that the router should call first to determine if it should deactivate this component after a navigation. Should return a <code>boolean&verbar;UrlTree</code> or an Observable/Promise that resolves to a <code>boolean&verbar;UrlTree</code>. |
| <code-example format="typescript" hideCopy language="typescript"> function canActivateChildGuard: CanActivateChildFn = &NewLine;&nbsp; ( &NewLine;&nbsp;&nbsp;&nbsp; route: ActivatedRouteSnapshot, &NewLine;&nbsp;&nbsp;&nbsp; state: RouterStateSnapshot &NewLine;&nbsp; ) => { &hellip; } &NewLine; &NewLine;{ path: &hellip;, canActivateChild: [canActivateGuard], children: &hellip; } </code-example> | An interface for defining a function that the router should call first to determine if it should activate the child route. Should return a <code>boolean&verbar;UrlTree</code> or an Observable/Promise that resolves to a <code>boolean&verbar;UrlTree</code>. |
| <code-example format="typescript" hideCopy language="typescript"> function resolveGuard implements ResolveFn&lt;T&gt; = &NewLine;&nbsp; ( &NewLine;&nbsp;&nbsp;&nbsp; route: ActivatedRouteSnapshot, &NewLine;&nbsp;&nbsp;&nbsp; state: RouterStateSnapshot &NewLine;&nbsp; ) => { &hellip; } &NewLine; &NewLine;{ path: &hellip;, resolve: [resolveGuard] } </code-example> | An interface for defining a function that the router should call first to resolve route data before rendering the route. Should return a value or an Observable/Promise that resolves to a value. |
| <code-example format="typescript" hideCopy language="typescript"> function canLoadGuard: CanLoadFn = &NewLine;&nbsp; ( &NewLine;&nbsp;&nbsp;&nbsp; route: Route &NewLine;&nbsp; ) => { &hellip; } &NewLine; &NewLine;{ path: &hellip;, canLoad: [canLoadGuard], loadChildren: &hellip; } </code-example> | An interface for defining a function that the router should call first to check if the lazy loaded module should be loaded. Should return a <code>boolean&verbar;UrlTree</code> or an Observable/Promise that resolves to a <code>boolean&verbar;UrlTree</code>. |
</div>
<!-- links -->
<!-- external links -->
<!-- end links -->
@reviewed 2022-02-28