{"id":23302127,"url":"https://github.com/pujansrt/angular-cheatsheet","last_synced_at":"2025-06-30T10:37:13.476Z","repository":{"id":127199214,"uuid":"312984007","full_name":"pujansrt/angular-cheatsheet","owner":"pujansrt","description":"Commands, Patterns, Common Packages, Tricks and Tips on latest Angular Framework","archived":false,"fork":false,"pushed_at":"2022-03-24T02:24:37.000Z","size":52,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-06T22:22:21.095Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pujansrt.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-11-15T07:56:33.000Z","updated_at":"2024-05-24T11:30:51.000Z","dependencies_parsed_at":null,"dependency_job_id":"45aab1d9-9b67-46ee-89d1-a01422499cca","html_url":"https://github.com/pujansrt/angular-cheatsheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/pujansrt/angular-cheatsheet","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pujansrt%2Fangular-cheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pujansrt%2Fangular-cheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pujansrt%2Fangular-cheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pujansrt%2Fangular-cheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pujansrt","download_url":"https://codeload.github.com/pujansrt/angular-cheatsheet/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pujansrt%2Fangular-cheatsheet/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262756892,"owners_count":23359609,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-12-20T10:18:48.541Z","updated_at":"2025-06-30T10:37:13.429Z","avatar_url":"https://github.com/pujansrt.png","language":null,"readme":"## Angular Cheatsheet\nBASED ON https://angular.io/guide/cheatsheet\n\n\n```python\nnpm install --save @angular/cli       # install command line interface (CLI) for Angular apps\n\nng new Todo                           # Create new Todo project. Generates new Todo folder in current directory\nng serve                              # serve the app\n\n\nng g component my-new-component       # Component\tMyNewComponent will be created and added to app.module.ts\nng g directive my-new-directive       # new directive\nng g pipe my-new-pipe\nng g service my-new-service\n\n\nng g class my-new-class\nng g interface my-new-interface\nng g enum my-new-enum\nng g module my-module\n\n\nng build                              # build the release\nng build --prod --base-href /aws/\nng build --prod --output-hashing none\nng build --prod --base-href /aws/ --output-path ~/Sites/aws\n```\n\n\n### BOOSTRAPPING\nhttps://angular.io/guide/bootstrapping\nhttps://angular.io/guide/ngmodules\n\n```js\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\n\n// Bootstraps the app, using the root component from the specified NgModule.\nplatformBrowserDynamic().bootstrapModule(AppModule); \n\n\nimport { NgModule } from '@angular/core';\n\n@NgModule({\n  declarations: ...,\n  imports: ...,\n  exports: ...,\n  providers: ...,\n  bootstrap: ...\n})\n\n// Defines a module that contains components, directives, pipes, and providers.\nclass MyModule {} \n\n// List of components, directives, and pipes that belong to this module.\ndeclarations: [MyRedComponent, MyBlueComponent, MyDatePipe] \n\n// List of modules to import into this module. Everything from the imported modules is available to declarations of this module.\nimports: [BrowserModule, SomeOtherModule] \n\n// List of components, directives, and pipes visible to modules that import this module.\nexports: [MyRedComponent, MyDatePipe] \n\n// List of dependency injection providers visible both to the contents of this module and to importers of this module.\nproviders: [MyService, { provide: ... }]  \n\n// List of components to bootstrap when this module is bootstrapped.\nbootstrap: [MyAppComponent] \n```\n\n### TEMPLATE SYNTAX\nhttps://angular.io/guide/template-syntax\n\n#### Style\n```js\n\u003c!-- Binds attribute role to the result of expression myAriaRole. --\u003e\n\u003cdiv [attr.role]=\"myAriaRole\"\u003e  \n\n\u003cdiv [class.extra-sparkle]=\"isDelightful\"\u003e  \n\u003cdiv [style.width.px]=\"mySize\"\u003e \n\u003ci class=\"fa\" [ngClass]=\"{'fa-heart-o': !item.id,'fa-heart': product.wishid}\" (click)=\"list(item)\"\u003e\u003c/i\u003e\n\u003cdiv class=\"form-group\" [ngClass]=\"{ 'has-error': f.submitted \u0026\u0026 !username.valid }\"\u003e...\u003c/div\u003e\n\n// Allows you to assign styles to an HTML element using CSS.\n\u003cdiv [ngStyle]=\"{'property': 'value'}\"\u003e\n\u003cdiv [ngStyle]=\"dynamicStyles()\"\u003e \n```\n\n#### Main\n```js\n\u003cinput [value]=\"firstName\"\u003e \u003c!-- Binds property value to the result of expression firstName --\u003e\n  \n\u003c!-- Calls method readRainbow defined in its component.ts file when a click event is triggered on this button--\u003e\n\u003cbutton (click)=\"readRainbow($event)\"\u003e  \n\n\u003cdiv title=\"Hello {{ponyName}}\"\u003e  \n\u003cp\u003eHello {{ponyName}}\u003c/p\u003e \n\u003cp\u003eEmployer: {{employer?.companyName}}\u003c/p\u003e \u003c!-- If employer exists then print companyName --\u003e\n\n\u003c!-- Sets up two-way data binding. Equivalent to: \u003cmy-cmp [title]=\"name\" (titleChange)=\"name=$event\"\u003e --\u003e\n\u003cmy-cmp [(title)]=\"name\"\u003e \n\n\u003c!-- Creates a local variable movieplayer that provides access to the video element instance in  data-binding and event-binding expressions in the current template. --\u003e\n\u003cvideo #movieplayer ...\u003e\n  \u003cbutton (click)=\"movieplayer.play()\"\u003e\n\u003c/video\u003e  \n\n\u003c!-- The * symbol turns the current element into an embedded template. Equivalent to: \u003cng-template [myUnless]=\"myExpression\"\u003e\u003cp\u003e...\u003c/p\u003e\u003c/ng-template\u003e --\u003e\n\u003cp *myUnless=\"myExpression\"\u003e...\u003c/p\u003e \n\n\u003c!-- Transforms the current value of expression cardNumber via the pipe called myCardNumberFormatter. --\u003e\n\u003cp\u003eCard No.: {{cardNumber | myCardNumberFormatter}}\u003c/p\u003e \n```\n\n#### Loop\n##### Table\n\n```js\n\u003ctable\u003e\n    \u003cthead\u003e\n        \u003cth\u003eName\u003c/th\u003e\n        \u003cth\u003eIndex\u003c/th\u003e\n    \u003c/thead\u003e\n    \u003ctbody\u003e\n        \u003ctr *ngFor=\"let hero of heroes\"\u003e\n            \u003ctd\u003e{{hero.name}}\u003c/td\u003e\n        \u003c/tr\u003e\n    \u003c/tbody\u003e\n\u003c/table\u003e\n```\n\n##### Other Loop\n```js\n\u003cdiv *ngFor=\"let hero of heroes; let i=index\"\u003e{{i + 1}} - {{hero.fullName}}\u003c/div\u003e  \n\n\u003cli *ngFor=\"let item of items; let i = index; trackBy: trackByFn\"\u003e\u003c/li\u003e\n\n\u003cselect id=\"jarfile\" (change)=\"sh(w)\" name=\"jarfile\" [(ngModel)]=\"w.jarfile\"\u003e\n   \u003coption *ngFor=\"let t of jars\" [value]=\"t\" [attr.selected]=\"w.jarfile==t ? true : null\"\u003e{{t}}\u003c/option\u003e\n\u003c/select\u003e\n```\n\n##### Print Items\n```js\n\u003cdiv *ngFor=\"let item of items; let firstItem = first; let lastItem = last\"\u003e\n  \u003cp *ngIf=\"firstItem\"\u003eI am the first item and I am gonna be showed\u003c/p\u003e\n  \u003cp *ngIf=\"!firstItem\"\u003eI am not the first item and I will not show up :(\u003c/p\u003e\n  \u003cp *ngIf=\"lastItem\"\u003eBut I'm gonna be showed as I am the last item :)\u003c/p\u003e\n\u003c/div\u003e\n```\n\n### BUILT-IN DIRECTIVES\nhttps://angular.io/guide/attribute-directives\n\n```js\nimport { CommonModule } from '@angular/common';\n\n\u003csection *ngIf=\"showSection\"\u003e \n\n\u003cli *ngFor=\"let item of list\"\u003e  \n\n// Conditionally swaps the contents of the div by selecting one of the embedded templates based on \n// the current value of conditionExpression.\n\u003cdiv [ngSwitch]=\"conditionExpression\"\u003e\n\u003cng-template [ngSwitchCase]=\"case1Exp\"\u003e...\u003c/ng-template\u003e\n\u003cng-template ngSwitchCase=\"case2LiteralString\"\u003e...\u003c/ng-template\u003e\n\u003cng-template ngSwitchDefault\u003e...\u003c/ng-template\u003e\n\u003c/div\u003e \n```\n\n### FORMS\nhttps://angular.io/guide/forms\n\n```js\n// app.module.ts\nimport { FormsModule } from '@angular/forms';\n\n@NgModule({\n  declarations: [...],\n  imports: [\n    ...,\n    FormsModule,\n  ],\n  providers: [...],\n  bootstrap: [AppComponent]\n})\n\n// Provides two-way data-binding, parsing, and validation for form controls.\n\u003cinput [(ngModel)]=\"userName\"\u003e  \n```\n\n### CLASS DECORATORS\n\n```js\nimport { Directive, ... } from '@angular/core';\n\n@Component({...}) // Declares that a class is a component and provides metadata about the component.\nclass MyComponent() {}  \n\n@Directive({...}) // Declares that a class is a directive and provides metadata about the directive.\nclass MyDirective() {}  \n\n@Pipe({...})  \t\t// Declares that a class is a pipe and provides metadata about the pipe.\nclass MyPipe() {} \n\n@Injectable()\t\t\t// Declares that a class can be injected into the constructor of another class \nclass MyService() {}  \n```\n\n### COMPONENT CHANGE DETECTION AND LIFECYCLE HOOKS\n\n```js\n// Called before any other lifecycle hook. Avoid any serious work here.\nconstructor(myService: MyService, ...) { ... }  \n\n// Called after every change to input properties and before processing content or child views.\nngOnChanges(changeRecord) { ... } \n\n// Called after the constructor, initializing input properties, and the first call to ngOnChanges.\nngOnInit() { ... }  \n\n// Called every time that the input properties of a component or a directive are checked. Use it\n// to extend change detection by performing a custom check.\nngDoCheck() { ... } \n\n// Called after ngOnInit when the component's or directive's content has been initialized.\nngAfterContentInit() { ... }  \n\n// Called after every check of the component's or directive's content.\nngAfterContentChecked() { ... } \n\n// Called after ngAfterContentInit when the component's views+child views/that a directive has been initialized.\nngAfterViewInit() { ... } \n\n// Called after every check of the component's views and child views / the view that a directive is in.\nngAfterViewChecked() { ... }  \n\n// Called once, before the instance is destroyed.\nngOnDestroy() { ... } \n```\n\n### DEPENDENCY INJECTION CONFIGURATION\nhttps://angular.io/guide/dependency-injection\n\n```js\n// Sets or overrides the provider for MyService to the MyMockService class.\n{ provide: MyService, useClass: MyMockService } \n\n// Sets or overrides the provider for MyService to the myFactory factory function.\n{ provide: MyService, useFactory: myFactory } \n\n// Sets or overrides the provider for MyValue to the value 41.\n{ provide: MyValue, useValue: 41 }  \n```\n### ROUTING AND NAVIGATION\nhttps://angular.io/guide/router\n\n```js\nimport { Routes, RouterModule, ... } from '@angular/router';\n\nconst 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\n// Configures routes for the application. Supports static, parameterized, redirect, and wildcard \n// routes. Also supports custom route data and resolve.\nconst routing = RouterModule.forRoot(routes); \n\n// Marks the location to load the component of the active route.\n\u003crouter-outlet\u003e\u003c/router-outlet\u003e\n\u003crouter-outlet name=\"aux\"\u003e\u003c/router-outlet\u003e\n\n// Creates a link to a different view based on a route instruction consisting of a route path, \n// required and optional parameters, query parameters, and a fragment. To navigate to a root \n// route, use the / prefix; for a child route, use the ./prefix; for a sibling or parent, use the \n// ../ prefix.\n\n\u003ca routerLink=\"/path\"\u003e\n\u003ca [routerLink]=\"[ '/path', routeParam ]\"\u003e\n\u003ca [routerLink]=\"[ '/path', { matrixParam: 'value' } ]\"\u003e\n\u003ca [routerLink]=\"[ '/path' ]\" [queryParams]=\"{ page: 1 }\"\u003e\n\u003ca [routerLink]=\"[ '/path' ]\" fragment=\"anchor\"\u003e\n\n// The provided classes are added to the element when the routerLink becomes the current active\n// route.\n\u003ca [routerLink]=\"[ '/path' ]\" routerLinkActive=\"active\"\u003e  \n\nclass CanActivateGuard implements CanActivate {\n  canActivate(\n    route: ActivatedRouteSnapshot,\n    state: RouterStateSnapshot\n  ): Observable\u003cboolean\u003e|Promise\u003cboolean\u003e|boolean { ... }\n}\n\n// An interface for defining a class that the router should call first to determine if it should \n// activate this component. Should return a boolean or an Observable/Promise that resolves to a boolean.\n{\n  path: ...,\n  canActivate: [CanActivateGuard]\n}  \n\nclass CanDeactivateGuard implements CanDeactivate\u003cT\u003e {\n  canDeactivate(\n    component: T,\n    route: ActivatedRouteSnapshot,\n    state: RouterStateSnapshot\n  ): Observable\u003cboolean\u003e|Promise\u003cboolean\u003e|boolean { ... }\n}\n\n// An interface for defining a class that the router should call first to determine if it should \n// deactivate this component after a navigation. Should return a boolean or an Observable/Promise \n// that resolves to a boolean.\n{\n  path: ...,\n  canDeactivate: [CanDeactivateGuard]\n}\n\nclass CanActivateChildGuard implements CanActivateChild {\n  canActivateChild(\n    route: ActivatedRouteSnapshot,\n    state: RouterStateSnapshot\n  ): Observable\u003cboolean\u003e|Promise\u003cboolean\u003e|boolean { ... }\n}\n\n// An interface for defining a class that the router should call first to determine if it should \n// activate the child route. Should return a boolean or an Observable/Promise that resolves to a  boolean.\n{\n  path: ...,\n  canActivateChild: [CanActivateGuard],\n  children: ...\n}\n\nclass ResolveGuard implements Resolve\u003cT\u003e {\n  resolve(\n    route: ActivatedRouteSnapshot,\n    state: RouterStateSnapshot\n  ): Observable\u003cany\u003e|Promise\u003cany\u003e|any { ... }\n}\n\n// An 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  path: ...,\n  resolve: [ResolveGuard]\n}\n\nclass CanLoadGuard implements CanLoad {\n  canLoad(\n    route: Route\n  ): Observable\u003cboolean\u003e|Promise\u003cboolean\u003e|boolean { ... }\n}\n\n// 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.\n{\n  path: ...,\n  canLoad: [CanLoadGuard],\n  loadChildren: ...\n}\n```\n\n\n## Input and Output\n\n### Input\n\n**Input()** To pass value into child component\n\n```js\n// hero-parent.component.ts\nimport { Component } from '@angular/core';\n\n@Component({\n  selector: 'app-hero-parent',\n  template: `\u003ch2\u003e{{master}} controls {{heroes.length}} heroes\u003c/h2\u003e\n\u003capp-hero-child *ngFor=\"let hero of heroes\" [hero]=\"hero\" [master]=\"master\"\u003e\n\u003c/app-hero-child\u003e`\n})\nexport class HeroParentComponent {\n  heroes = [\n    { name: 'Superman', location: 'Hong Kong' },\n    { name: 'Spiderman', location: 'Dallas' },\n    { name: 'Ironman', location: 'Delhi' },\n  ];\n  master = 'Master';\n}\n```\n\n```js\n// hero-child.component.ts\n@Component({\n  selector: 'app-hero-child',\n  template: `\u003ch3\u003e{{hero.name}} says:\u003c/h3\u003e\u003cp\u003eI, {{hero.name}}, am at your service in {{hero.location}}, {{master}}.\u003c/p\u003e`\n})\nexport class HeroChildComponent {\n  @Input() hero;\n  @Input() master;\n}\n```\n\nOutput shows when load `\u003capp-hero-parent\u003e` in app.component.html\n\n```html\nMaster controls 3 heroes\nSuperman says:\nI, Superman, am at your service in Hong Kong, Master\nSpiderman says:\nI, Spiderman, am at your service in Dallas, Master\nIronman says:\nI, Ironman, am at your service in Delhi, Master\n```\n\n\n\n### Output\n\n**Output()** Emiting event to parent component\n\n```js\nimport {Component, Input, Output, EventEmitter} from '@angular/core';\n\n@Component({\n    selector: 'yc',\n    template: `\u003cxc (notifyFromX)='onNotify($event)'\u003e\u003c/xc\u003e`\n})\n\nexport class ChildComponent {\n    @Output() notifyFromY: EventEmitter\u003cstring\u003e = new EventEmitter\u003cstring\u003e();\n\n    constructor(){}\n\n    onNotify(message:string):void {\n        //console.log(message, new Date());\n        this.notifyFromY.emit(message + ' Y ---\u003e');\n    }\n}\n```\n\n### AuthGuard\n\n```js\nRouterModule.forRoot([\n    ...,\n    { path: 'check-out', component: CheckOutComponent, canActivate: [AuthGuard] },\n    { path: 'admin/products/new', component: AdminProductEditComponent, canActivate: [AuthGuard, AdminAuthGuard] },\n    { path: 'admin/products/:id', component: AdminProductEditComponent, canActivate: [AuthGuard, AdminAuthGuard] }\n]);\n```\n\n```js\n@Injectable({\n  providedIn: 'root'\n})\nexport class AuthGuard implements CanActivate {\n\n  constructor(public authService: AuthService, public router: Router) {}\n\n  canActivate(\n    next: ActivatedRouteSnapshot,\n    state: RouterStateSnapshot): Observable\u003cboolean\u003e | Promise\u003cboolean\u003e | boolean {\n    if (this.authService.isLoggedIn !== true) {\n      this.router.navigate(['login']);\n    }\n    return true;\n  }\n}\n```\n\n```js\n@Injectable({\n  providedIn: 'root'\n})\nexport class AdminAuthGuard implements CanActivate {\n\n  constructor(public authService: AuthService, public router: Router) {\n  }\n\n  canActivate(\n    next: ActivatedRouteSnapshot,\n    state: RouterStateSnapshot): Observable\u003cboolean\u003e | Promise\u003cboolean\u003e | boolean {\n\n    if (this.authService.isLoggedIn !== true) {\n      this.router.navigate(['login']);\n    }\n\n    if (!this.authService.isAdmin) {\n      this.router.navigate(['not-found']);\n    }\n\n    return true;\n  }\n}\n```\n\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpujansrt%2Fangular-cheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpujansrt%2Fangular-cheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpujansrt%2Fangular-cheatsheet/lists"}