{ "id": "guide/cheatsheet", "title": "Cheat Sheet", "contents": "\n\n\n
Bootstrapping | \n
| \n
---|---|
platformBrowserDynamic().bootstrapModule(AppModule); | \nBootstraps the app, using the root component from the specified | \n
NgModules | \n
| \n
---|---|
@NgModule({\n declarations: ..., imports: ..., exports: ...,\n providers: ..., bootstrap: ...\n})\nclass MyModule {}\n | \nDefines a module that contains components, directives, pipes, and providers. \n | \n
declarations: [MyRedComponent, MyBlueComponent, MyDatePipe] | \nList of components, directives, and pipes that belong to this module. \n | \n
imports: [BrowserModule, SomeOtherModule] | \nList of modules to import into this module. Everything from the imported modules\nis available to | \n
exports: [MyRedComponent, MyDatePipe] | \nList of components, directives, and pipes visible to modules that import this module. \n | \n
providers: [MyService, { provide: ... }] | \nList of dependency injection providers visible both to the contents of this module and to importers of this module. \n | \n
entryComponents: [SomeComponent, OtherComponent] | \nList of components not referenced in any reachable template, for example dynamically created from code. | \n
bootstrap: [MyAppComponent] | \nList of components to bootstrap when this module is bootstrapped. \n | \n
Template syntax | \n\n |
---|---|
<input [value]=\"firstName\"> | \nBinds property | \n
<div [attr.role]=\"myAriaRole\"> | \nBinds attribute | \n
<div [class.extra-sparkle]=\"isDelightful\"> | \nBinds the presence of the CSS class | \n
<div [style.width.px]=\"mySize\"> | \nBinds style property | \n
<button (click)=\"readRainbow($event)\"> | \nCalls method | \n
<div title=\"Hello {{ponyName}}\"> | \nBinds a property to an interpolated string, for example, \"Hello Seabiscuit\". Equivalent to:\n | \n
<p>Hello {{ponyName}}</p> | \nBinds text content to an interpolated string, for example, \"Hello Seabiscuit\". \n | \n
<my-cmp [(title)]=\"name\"> | \nSets up two-way data binding. Equivalent to: | \n
<video #movieplayer ...></video>\n<button (click)=\"movieplayer.play()\">Play</button>\n | \nCreates a local variable | \n
<p *myUnless=\"myExpression\">...</p> | \nThe | \n
<p>Card No.: {{cardNumber | myCardNumberFormatter}}</p> | \nTransforms the current value of expression | \n
<p>Employer: {{employer?.companyName}}</p> | \nThe safe navigation operator ( | \n
<svg:rect x=\"0\" y=\"0\" width=\"100\" height=\"100\"/> | \nAn SVG snippet template needs an | \n
<svg>\n <rect x=\"0\" y=\"0\" width=\"100\" height=\"100\"/>\n</svg>\n | \nAn | \n
Built-in directives | \n
| \n
---|---|
<section *ngIf=\"showSection\"> | \nRemoves or recreates a portion of the DOM tree based on the | \n
<li *ngFor=\"let item of list\"> | \nTurns the li element and its contents into a template, and uses that to instantiate a view for each item in list. \n | \n
<div [ngSwitch]=\"conditionExpression\">\n <ng-template [ngSwitchCase]=\"case1Exp\">...</ng-template>\n <ng-template ngSwitchCase=\"case2LiteralString\">...</ng-template>\n <ng-template ngSwitchDefault>...</ng-template>\n</div>\n | \nConditionally swaps the contents of the div by selecting one of the embedded templates based on the current value of | \n
<div [ngClass]=\"{'active': isActive, 'disabled': isDisabled}\"> | \nBinds 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. \n | \n
<div [ngStyle]=\"{'property': 'value'}\">\n<div [ngStyle]=\"dynamicStyles()\">\n | \nAllows 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. \n | \n
Forms | \n
| \n
---|---|
<input [(ngModel)]=\"userName\"> | \nProvides two-way data-binding, parsing, and validation for form controls. \n | \n
Class decorators | \n
| \n
---|---|
@Component({...})\nclass MyComponent() {}\n | \nDeclares that a class is a component and provides metadata about the component. \n | \n
@Directive({...})\nclass MyDirective() {}\n | \nDeclares that a class is a directive and provides metadata about the directive. \n | \n
@Pipe({...})\nclass MyPipe() {}\n | \nDeclares that a class is a pipe and provides metadata about the pipe. \n | \n
@Injectable()\nclass MyService() {}\n | \nDeclares 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. \n | \n
Directive configuration | \n
| \n
---|---|
selector: '.cool-button:not(a)' | \nSpecifies a CSS selector that identifies this directive within a template. Supported selectors include Does not support parent-child relationship selectors. \n | \n
providers: [MyService, { provide: ... }] | \nList of dependency injection providers for this directive and its children. \n | \n
Component configuration | \n\n | \n
---|---|
moduleId: module.id | \nIf set, the | \n
viewProviders: [MyService, { provide: ... }] | \nList of dependency injection providers scoped to this component's view. \n | \n
template: 'Hello {{name}}'\ntemplateUrl: 'my-component.html'\n | \nInline template or external template URL of the component's view. \n | \n
styles: ['.primary {color: red}']\nstyleUrls: ['my-component.css']\n | \nList of inline CSS styles or external stylesheet URLs for styling the component’s view. \n | \n
Class field decorators for directives and components | \n
| \n
---|---|
@Input() myProperty; | \nDeclares an input property that you can update via property binding (example:\n | \n
@Output() myEvent = new EventEmitter(); | \nDeclares an output property that fires events that you can subscribe to with an event binding (example: | \n
@HostBinding('class.valid') isValid; | \nBinds a host element property (here, the CSS class | \n
@HostListener('click', ['$event']) onClick(e) {...} | \nSubscribes to a host element event ( | \n
@ContentChild(myPredicate) myChildComponent; | \nBinds the first result of the component content query ( | \n
@ContentChildren(myPredicate) myChildComponents; | \nBinds the results of the component content query ( | \n
@ViewChild(myPredicate) myChildComponent; | \nBinds the first result of the component view query ( | \n
@ViewChildren(myPredicate) myChildComponents; | \nBinds the results of the component view query ( | \n
Directive and component change detection and lifecycle hooks | \n(implemented as class methods)\n \n | \n
---|---|
constructor(myService: MyService, ...) { ... } | \nCalled before any other lifecycle hook. Use it to inject dependencies, but avoid any serious work here. \n | \n
ngOnChanges(changeRecord) { ... } | \nCalled after every change to input properties and before processing content or child views. \n | \n
ngOnInit() { ... } | \nCalled after the constructor, initializing input properties, and the first call to | \n
ngDoCheck() { ... } | \nCalled 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. \n | \n
ngAfterContentInit() { ... } | \nCalled after | \n
ngAfterContentChecked() { ... } | \nCalled after every check of the component's or directive's content. \n | \n
ngAfterViewInit() { ... } | \nCalled after | \n
ngAfterViewChecked() { ... } | \nCalled after every check of the component's views and child views / the view that a directive is in. \n | \n
ngOnDestroy() { ... } | \nCalled once, before the instance is destroyed. \n | \n
Dependency injection configuration | \n\n |
---|---|
{ provide: MyService, useClass: MyMockService } | \nSets or overrides the provider for | \n
{ provide: MyService, useFactory: myFactory } | \nSets or overrides the provider for | \n
{ provide: MyValue, useValue: 41 } | \nSets or overrides the provider for | \n
Routing and navigation | \n
| \n
---|---|
const routes: Routes = [\n { path: '', component: HomeComponent },\n { path: 'path/:routeParam', component: MyComponent },\n { path: 'staticPath', component: ... },\n { path: '**', component: ... },\n { path: 'oldPath', redirectTo: '/staticPath' },\n { path: ..., component: ..., data: { message: 'Custom' } }\n]);\n
| \nConfigures routes for the application. Supports static, parameterized, redirect, and wildcard routes. Also supports custom route data and resolve. \n | \n
<router-outlet></router-outlet>\n<router-outlet name=\"aux\"></router-outlet>\n | \nMarks the location to load the component of the active route. \n | \n
<a routerLink=\"/path\">\n<a [routerLink]=\"[ '/path', routeParam ]\">\n<a [routerLink]=\"[ '/path', { matrixParam: 'value' } ]\">\n<a [routerLink]=\"[ '/path' ]\" [queryParams]=\"{ page: 1 }\">\n<a [routerLink]=\"[ '/path' ]\" fragment=\"anchor\">\n | \nCreates 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 | \n
<a [routerLink]=\"[ '/path' ]\" routerLinkActive=\"active\"> | \nThe provided classes are added to the element when the | \n
class CanActivateGuard implements CanActivate {\n canActivate(\n route: ActivatedRouteSnapshot,\n state: RouterStateSnapshot\n ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree { ... }\n}\n
| \nAn interface for defining a class that the router should call first to determine if it should activate this component. Should return a boolean|UrlTree or an Observable/Promise that resolves to a boolean|UrlTree. \n | \n
class CanDeactivateGuard implements CanDeactivate<T> {\n canDeactivate(\n component: T,\n route: ActivatedRouteSnapshot,\n state: RouterStateSnapshot\n ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree { ... }\n}\n
| \nAn 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|UrlTree or an Observable/Promise that resolves to a boolean|UrlTree. \n | \n
class CanActivateChildGuard implements CanActivateChild {\n canActivateChild(\n route: ActivatedRouteSnapshot,\n state: RouterStateSnapshot\n ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree { ... }\n}\n
| \nAn interface for defining a class that the router should call first to determine if it should activate the child route. Should return a boolean|UrlTree or an Observable/Promise that resolves to a boolean|UrlTree. \n | \n
class ResolveGuard implements Resolve<T> {\n resolve(\n route: ActivatedRouteSnapshot,\n state: RouterStateSnapshot\n ): Observable<any>|Promise<any>|any { ... }\n}\n
| \nAn interface for defining a class 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. \n | \n
class CanLoadGuard implements CanLoad {\n canLoad(\n route: Route\n ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree { ... }\n}\n
| \nAn 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|UrlTree or an Observable/Promise that resolves to a boolean|UrlTree. \n | \n