[
  {
    "path": "README.md",
    "content": "# Angular Cheatsheet\nSet of basic functionalities from Angular in one place. Thanks to http://foreach.pl for contribute\n\n**Check also other Cheatsheets:**\n\n[TypeScript](https://github.com/delprzemo/typescript-cheatsheet)\n\n[ReactJS](https://github.com/delprzemo/react-cheatsheet)\n\n# Table of Contents\n\n\n<!--ts-->\n   * [AngularCli](#AngularCLI)\n   * [Components and Templates](#Components-and-Templates)\n      * [Sample component ts file](#Sample-component-ts-file)\n      * [Component life cycles](#Component-life-cycles)\n      * [Template syntax](#Template-syntax)\n      * [Input and Output](#Input-and-Output)\n      * [Content projection](#Content-projection)\n      * [ViewChild decorator](#ViewChild-decorator)\n   * [Routing](#Routing)\n      * [CanActivate and CanDeactivate](#CanActivate-and-CanDeactivate)\n   * [Modules](#Modules)\n   * [Services](#Services)\n      * [HttpClient](#HttpClient)\n      * [Dependency Injection](#Dependency-Injection)\n      * [Declare global values](#Declare-global-values)\n   * [Pipes](#Pipes)\n   * [Directives](#Directives)\n   * [Animations](#Animations)\n   * [Angular Forms](#Angular-Forms)\n      * [Template driven forms](#Template-driven-forms)\n      * [Reactive forms](#Reactive-forms)\n      * [Custom Validator for Reactive forms](#Custom-Validator-for-Reactive-forms)\n      * [Custom Validator Directive for Template driven forms](#Custom-Validator-Directive-for-Template-driven-forms)\n      * [ngModel in custom component](#ngModel-in-custom-component)\n   * [Tests](#Tests)\n      * [Unit tests](#Unit-tests)\n   * [Others](#Others)\n      * [Http interceptor](#Http-interceptor)\n      * [host](#host)\n   * [Interview questions](#Interview-questions)\n<!--te-->\n\n\nAngularCLI\n=================\n\nCommand line inferface for Angular - set of commands that will help us during development.\n\n**1. Setup**\n\n| Command  | Description |\n| ------------- | ------------- |\n| npm install -g @angular/cli  | Install Angular CLI globally |\n\n**2. New application**\n\n| Command  | Description |\n| ------------- | ------------- |\n| ng new best-practises --dry-run  | just simulate ng new  |\n| ng new best-practises --skip-install  | skip install means don't run npm install  |\n| ng new best-practises --prefix best  | set prefix to best  |\n| ng new --help\t| check available command list  |\n\n\n**3. Lint - check and make sure that our code if free of code smells/ bad formatting**\n\n| Command  | Description |\n| ------------- | ------------- |\n| ng lint my-app --help  | check available command list  |\n| ng lint my-app --format stylish  | format code  |\n| ng lint my-app --fix   | fix code smells  |\n| ng lint my-app  | show warnings  |\n\n\n**4. Blueprints**\n\n| Command  | Description |\n| ------------- | ------------- |\n| ng g c my-component --flat true  | don't create new folder for this component  |\n| --inline-template (-t)  | will the template be in .ts file?  |\n| --inline-style (-s) \t  | will the style be in .ts file?  |\n| --spec\t\t  | generate spec?  |\n| --prefix  | assign own prefix  |\n| ng g d directive-name\t  | create directive  |\n| ng g s service-name\t  | create service |\n| ng g cl models/customer\t  | create customer class in models folder |\n| ng g i models/person  | create create interface in models folder |\n| ng g e models/gender  | create  create ENUM gender in models folder |\n| ng g p init-caps\t  | create create pipe  |\n\n**5. Building&Serving**\n\n| Command  | Description |\n| ------------- | ------------- |\n| ng build   | build app to /dist folder  |\n| ng build --aot  | build app without code that we don't need (optimatization)  |\n| ng build --prod\t  | build for production  |\n| ng serve -o   | serve with opening a browser  |\n| ng serve --live-reload\t  | reload when changes occur  |\n| ng serve -ssl   | serving using SSL  |\n\n**6. Add new capabilities**\n\n| Command  | Description |\n| ------------- | ------------- |\n| ng add @angular/material \t  | add angular material to project  |\n| ng g @angular/material:material-nav --name nav  | create material navigation component  |\n\n# Components and Templates\n\nComponents are the most basic UI building block of an Angular app. An Angular app contains a tree of Angular components.\n\n## Sample component ts file\n```ts\nimport { Component } from '@angular/core';\n\n@Component({\n\t// component attributes\n\tselector: 'app-root',\n\ttemplateUrl: './app.component.html',\n\tstyleUrls: ['./app.component.less']\n})\n\nexport class AppComponent {\n\ttitle = 'my-dogs-training';\n}\n```\n\n## Component attributes\n\n\n| Attribute  | Description |\n| ------------- | ------------- |\n| changeDetection\t  | The change-detection strategy to use for this component.  |\n| viewProviders  | \tDefines the set of injectable objects that are visible to its view DOM children  |\n| moduleId  | The module ID of the module that contains the component  |\n| encapsulation  | \tAn encapsulation policy for the template and CSS styles  |\n| interpolation  | \tOverrides the default encapsulation start and end delimiters ({{ and }}  |\n| entryComponents  | \tA set of components that should be compiled along with this component.  |\n| preserveWhitespaces  | \tTrue to preserve or false to remove potentially superfluous whitespace characters from the compiled template.   |\n\n## Component life cycles\n\n| Life cycle  | Description |\n| ------------- | ------------- |\n| ngOnInit  | Called once, after the first ngOnChanges()   |\n| ngOnChanges  | Called before ngOnInit() and whenever one of input properties change.   |\n| ngOnDestroy  | Called just before Angular destroys the directive/component  |\n| ngDoCheck  | Called during every change detection run  |\n| ngAfterContentChecked  | Called after the ngAfterContentInit() and every subsequent ngDoCheck()  |\n| ngAfterViewChecked  | Called after the ngAfterViewInit() and every subsequent ngAfterContentChecked().  |\n| ngAfterContentInit  | Called once after the first ngDoCheck().  |\n| ngAfterViewInit  | Called once after the first ngAfterContentChecked().   |\n\n## Template syntax\n\n| Syntax  | Description |\n| ------------- | ------------- |\n| {{user.name}}\t| Interpolation - just generate user name here  |\n| <img [src] = \"user.imageUrl\">\t| property binding - bind image url for user to src attribute  |\n| <button (click)=\"do()\" ... />\t| Event - assign function to click event  |\n| <button *ngIf=\"user.showSth\" ... />\t| Show button when user.showSth is true  |\n| *ngFor=\"let item of items\"\t| Iterate through items list |\n| <div [ngClass]=\"{green: isTrue(), bold: itTrue()}\"/> | Angular ngClass attribute  |\n| <div [ngStyle]=\"{'color': isTrue() ? '#bbb' : '#ccc'}\"/>\t| Angular ngStyle attribute  |\n\n## Input and Output\n\n**Input()**\nTo pass value into child component\n\nSample child component implementation\n```ts\nexport class SampleComponent {\n\t@Input() value: any/string/object/…;\n\t...\n}\n```\n\nSample parent component usage\n```html\n<app-sample-component [value]=\"myValue\"></app-sampe-component>\n```\n\n**Output()**\nEmiting event to parent component\n\nSample child component\n```ts\n@Output() myEvent: EventEmitter<MyModel> = new EventEmitter();\nonRemoved(item: MyModel) {\n\tthis.myEvent.emit(item);\n}\n```\n\nSample parent component\n```html\n<app-my-component \n(myEvent)=\"someFunction()\"></app-my-component>\n```\n\nonRemoved in child component is calling someFunction in parent component\n\n## Content projection\nContent projection is injection inner html into child component\n\nExample:\n\n**Parent component template**\n```html\n<component>\n\t<div>\n\t\t(some html here)\n\t</div>\n</component>\n```\n\n**Child component template**\n```html \n<ng-content></ng-content>\n```\n(some html here) will be injection into <ng-content></ng-content>\n\n**Two differents htmls**\n```html\n<component>\n\t<div well-title>\n\t\t(some html here)\n\t</div>\n\t<div well-body>\n\t\t(some html here)\n\t</div>\n</component>\n```\n\n```html\n<ng-content select=\"title\"></ng-content> \n<ng-content select=\"body\"></ng-content>\n```\n\n## ViewChild decorator\nIn order to have access to child component/directive/element\n\n```ts\n@ViewChild(NumberComponent)\nprivate numberComponent: NumberComponent;\nincrease() {\nthis.numberComponent.increaseByOne(); //method from child component\n}\ndecrease() {\nthis.numberComponent.decreaseByOne();  //method from child component\n}\n```\n\n**Sample for element:**\nhtml:\n```html\n<div #myElement></div>\n```\n\ncomponent:\n```ts\n@ViewChild('myElement') myElement: ElementRef\n```\nInstead of ElementRef can be used specific element like FormControl for forms.\n\nReference to element in html:\n```html\n<button (click)=\"doSth(myElement)\"></button>\n```\n\n\n# Routing\nThe Angular Router enables navigation from one view to the next as users perform application tasks.\n\n**Sample routing ts file**\n```ts\nconst appRoutes: Routes = [\n  { path: 'crisis-center', component: CrisisListComponent },\n  { path: 'hero/:id',      component: HeroDetailComponent },\n  {\n    path: 'heroes',\n    component: HeroListComponent,\n    data: { title: 'Heroes List' }\n  },\n  { path: '',\n    redirectTo: '/heroes',\n    pathMatch: 'full'\n  },\n  { path: '**', component: PageNotFoundComponent }\n];\n```\n\nThen this should be added inside Angular.module imports\n```ts\nRouterModule.forRoot(appRoutes)\n```\n\nYou can also turn on console tracking for your routing by adding enableTracing\n\n```ts\nimports: [\n   RouterModule.forRoot(\n     routes,\n     {enableTracing: true}\n    )\n],\n ```\n\n**Usage**\n```html\n  <a routerLink=\"/crisis-center\" routerLinkActive=\"active\">Crisis Center</a>\t\n```\nrouterLinkActive=\"active\" will add active class to element when the link's route becomes active\n\n```ts\n//Navigate from code\nthis.router.navigate(['/heroes']);\n\n// with parameters\t\t\t\t\t\t\t\t\t\t\t\t\t\nthis.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);\n\n// Receive parameters without Observable\nlet id = this.route.snapshot.paramMap.get('id');\t\t\t\t\t\t\t\t\t\t\n ```\n \n## CanActivate and CanDeactivate\nInterface that a class can implement to be a guard deciding if a route can be activated. If all guards return true, navigation will continue. \n\n```ts\n\nclass AlwaysAuthGuard implements CanActivate {\t\n\tcanActivate() {\n\t\treturn true;\n\t}\n}\n```\nand assing it in routing module:\n\n```ts\n {\n    path: 'artist/:artistId',\n    component: ArtistComponent,\n    canActivate: [AlwaysAuthGuard], \n    children: [\n      {path: '', redirectTo: 'tracks'},\n      {path: 'tracks', component: ArtistTrackListComponent},\n      {path: 'albums', component: ArtistAlbumListComponent},\n    ]\n  }\n```\n\n# Modules\nAngular apps are modular and Angular has its own modularity system called NgModules. NgModules are containers for a cohesive block of code dedicated to an application domain, a workflow, or a closely related set of capabilities. \n\n## Sample module with comments\n\n```ts\nimport { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { AppRoutingModule } from './app-routing.module';\nimport { AppComponent } from './app.component';\n\n@NgModule({\n\tdeclarations: [AppComponent], // components, pipes, directives\n\timports: [BrowserModule, AppRoutingModule], // other modules\n\tproviders: [], // services\n\tbootstrap: [AppComponent] // top component\n})\nexport class AppModule { }\n```\n\n# Services\nComponents shouldn't fetch or save data directly and they certainly shouldn't knowingly present fake data. They should focus on presenting data and delegate data access to a service.\n\n**Sample service with one function**\n```ts\n@Injectable()\nexport class MyService {\n\tpublic items: Item[];\n\tconstructor() { }\n\t\n\tgetSth() {\n\t\t// some implementation\n\t}\n}\n```\n**Usage**\nIt should be injected before usage\n```ts \nconstructor(private dogListService: MyService) \n```\n\nand add in module:\n\n```ts\nproviders: [MyService]\n```\n\n## HttpClient\nTo handle and consume http requests\n\n1. Add import to module\n```ts\nimport { HttpClientModule} from \"@angular/common/http\";\n```\n\n2. Usage\n```ts\nimport {HttpClient} from '@angular/common/http';\n\n...\n\n// GET\npublic getData(): Observable<MyResponseModel> {\n\treturn this.http.get<MyResponseModel>('api/users/2');\n}\n\n// POST\npublic send(val1: any, val2: any): Observable<any> {\n\tconst object = new SendModel(val1, val2);\n\tconst options = {headers: new HttpHeaders({'Content-type': 'application/json'})};\n\treturn this.http.post<string>(environment.apiUrl + 'api/login', object, options);\n}\n\n\n```\n\n## Dependency Injection\n\nInject class into another class\n```ts\n@Injectable({\n\tprovidedIn: 'root',\n})\nexport class SomeService {}\n```\nIt accepts 'root' as a value or any module of your application\n\n## Declare global values\n\nclass:\n```ts\nimport {InjectionToken} from '@angular/core';\nexport const CONTROLS_GLOBAL_CONFIG = new InjectionToken<ControlsConfig>('global-values');\nexport interface ControlsConfig {firstGlobalValue: string;}\n```\n\nmodule:\n```ts\nproviders: [{provide: CONTROLS_GLOBAL_CONFIG, useValue: {firstGlobalValue : 'Some value' }},\n```\n\nusage (for example in component)\n```ts\nconstructor(@Optional() @Inject(CONTROLS_GLOBAL_CONFIG) globalVlues: ControlsConfig) {\n```\n\n# Pipes\nTransform data/value to specific format, for example:\n\nShow date in shortDate format:\n```html\n{{model.birthsDay | date:'shortDate'}}\n```\n\n**Pipe implementation**\n```ts\n@Pipe({name: 'uselessPipe'})\nexport class uselessPipe implements PipeTransform {\n  transform(value: string, before: string, after: string): string {\n    let newStr = `${before} ${value} ${after}`;\n    return newStr;\n  }\n}\n```\n\n**usage**\n```html\n{{ user.name | uselessPipe:\"Mr.\":\"the great\" }}\n```\n\n# Directives\nAn Attribute directive changes the appearance or behavior of a DOM element. For example [ngStyle] is a directive\n\n**Custom directive**\n```ts\nimport { Directive, ElementRef, HostListener, Input } from '@angular/core';\n\n@Directive({\n  selector: '[appHighlight]'\n})\nexport class HighlightDirective {\n\n  constructor(private el: ElementRef) { }\n\n  @Input('appHighlight') highlightColor: string;\n  @Input('otherPar') otherPar: any;     //it will be taken from other attribute named [otherPar]\n\n  @HostListener('mouseenter') onMouseEnter() {\n    this.highlight(this.highlightColor || 'red');\n  }\n\n  private highlight(color: string) {\n    this.el.nativeElement.style.backgroundColor = color;\n  }\n}\n```\n\n***Usage***\n```html\n<p [appHighlight]=\"color\" [otherPar]=\"someValue\">Highlight me!</p>\n```\n\n\n# Animations\nAnimations - moving from style state to another style state. Before add BrowserModule and BrowserAnimationsModule to module\n\n**Implementation:**\n```ts\n  animations: [\n      trigger('openClose', [\n        state('open', style({\n          height: '400px',\n          opacity: 1.5,\n        })),\n        state('closed', style({\n          height: '100px',\n          opacity: 0.5,\n        })),\n        transition('open => closed', [\n          animate('1s')\n        ]),\n        transition('closed => open', [\n          animate('1s')\n        ])\n      ])\n    ]\n```\n\n**usage**\n```html\n<div [@openClose]=\"isShowed ? 'open' : 'closed'\">\n```\n\n# Angular Forms\n\n## Template driven forms\nForm logic (validation, properties) are kept in template\n\n**sample html**\n```html\n<form name=\"form\" (ngSubmit)=\"f.form.valid && onSubmit()\" #f=\"ngForm\" novalidate>\n                    <div class=\"form-group\">\n                        <label for=\"firstName\">First Name</label>\n                        <input type=\"text\" class=\"form-control\" name=\"firstName\" [(ngModel)]=\"model.firstName\" #firstName=\"ngModel\" [ngClass]=\"{ 'is-invalid': f.submitted && firstName.invalid }\" required />\n                        <div *ngIf=\"f.submitted && firstName.invalid\" class=\"invalid-feedback\">\n                            <div *ngIf=\"firstName.errors.required\">First Name is required</div>\n                        </div>\n                    </div>\n                    <div class=\"form-group\">\n                        <button class=\"btn btn-primary\">Register</button>\n                    </div>\n                </form>\n```\n\n**sample component**\n```ts\n@ViewChild(\"f\") form: any;\nfirstName: string = \"\";\nlangs: string[] = [\"English\", \"French\", \"German\"];\n\nonSubmit() {\n\tif (this.form.valid) {\n\t\tconsole.log(\"Form Submitted!\");\n\t\tthis.form.reset();\n\t}\n}\n```\n\n## Reactive forms\nForm logic (validation, properties) are kept in component\n\n**sample html**\n```html\n<form [formGroup]=\"registerForm\" (ngSubmit)=\"onSubmit()\">\n\t<div class=\"form-group\">\n\t\t<label>Email</label>\n\t\t<input type=\"text\" formControlName=\"email\" class=\"form-control\" [ngClass]=\"{ 'is-invalid': submitted && f.email.errors }\" />\n\t\t<div *ngIf=\"submitted && f.email.errors\" class=\"invalid-feedback\">\n                            <div *ngIf=\"f.email.errors.required\">Email is required</div>\n                            <div *ngIf=\"f.email.errors.email\">Email must be a valid email address</div>\n \t\t</div>\n\t</div>\n\n\t<div class=\"form-group\">\n\t\t<button [disabled]=\"loading\" class=\"btn btn-primary\">Register</button>\n\t</div>\n </form>\n```\n\n**sample component**\n```ts\nregisterForm: FormGroup;\nsubmitted = false;\n\nconstructor(private formBuilder: FormBuilder) { }\n\nngOnInit() {\n\tthis.registerForm = this.formBuilder.group({\n\t\tfirstName: [{{here default value}}, Validators.required],\n\t\tlastName: ['', Validators.required],\n\t\temail: ['', [Validators.required, Validators.email]],\n\t\tpassword: ['', [Validators.required, Validators.minLength(6)]]\n\t});\n}\n\n// convenience getter for easy access to form fields\nget f() { return this.registerForm.controls; }\n\n onSubmit() {\n\t this.submitted = true;\n\n\t// stop here if form is invalid\n\tif (this.registerForm.invalid) {\n\t\treturn;\n\t}\n\n\talert('SUCCESS!! :-)')\n}\n```\n\n## Custom Validator for Reactive forms\n\n**Function**\n```ts\nvalidateUrl(control: AbstractControl) {\n    if (!control.value || control.value.includes('.png') || control.value.includes('.jpg')) {\n      return null;\n    }\n    return { validUrl: true };\n  }\n```\n\n**Usage**\n```ts\nthis.secondFormGroup = this._formBuilder.group({\n      imageCtrl: ['', [Validators.required, this.validateUrl]]\n});\n```\n\n**Multi-field validation**\n```ts\nvalidateNameShire(group: FormGroup) {\n    if (group) {\n      if (group.get('isShireCtrl').value && !group.get('nameCtrl').value.toString().toLowerCase().includes('shire')) {\n\treturn { nameShire : true };\n      }\n    }\n    return null;\n }\n```\n\n**Multi-field validation usage***\n```ts\nthis.firstFormGroup.setValidators(this.validateNameShire);\n```\n\n**Error handling**\n```html\n<div *ngIf=\"firstFormGroup.controls.nameCtrl.errors.maxlength\">Name is too long</div>\t\t\t\t\n<div *ngIf=\"firstFormGroup.errors.nameShire\">Shire dogs should have \"shire\" in name</div>\n```\n\n## Custom Validator Directive for Template driven forms\nTo register our custom validation directive to NG_VALIDATORS service we have to do it like this:\n(thanks to multi parameter we won't override NG_VALIDATORS but just add CustomValidator to NG_VALIDATORS)\n\n```ts\n@Directive({\n\tselector: '[CustomValidator]',\n\tproviders: [{provide: NG_VALIDATORS, useExisting: CustomValidator, multi:true}]\t\t\t\t\t\t\n})\n```\n\nExample:\n```ts\n@Directive({\n\tselector: '[customValidation]',\n\tproviders: [{provide: NG_VALIDATORS, useExisting: \tEmailValidationDirective, multi: true}]\n})\nexport class CustomValidation implements Validator {\n\tconstructor() { }\n\tvalidate(control: AbstractControl): ValidationErrors {\n\treturn (control.value && control.value.length <= 300) ? \n\t\t{myValue : true } : null;\n\t}\n}\n```\n\nFor multiple fields:\n```ts\nvalidate(formGroup: FormGroup): ValidationErrors {\n\tconst passwordControl = formGroup.controls[\"password\"];\n\tconst emailControl = formGroup.controls[\"login\"];\n\tif (!passwordControl || !emailControl || !passwordControl.value || !emailControl.value) {\n\t\treturn null;\n\t}\n\n\tif (passwordControl.value.length > emailControl.value.length) {\n\t\tpasswordControl.setErrors({ tooLong: true });\n\t} else {\n\t\tpasswordControl.setErrors(null);\n\t}\n\treturn formGroup;\n}\n\n```\n\n## ngModel in custom component\n\n1. Add to module:\n```ts\nproviders: [\n\t{\n\t\tprovide: NG_VALUE_ACCESSOR,\n\t\tuseExisting: forwardRef(() => TextAreaComponent),\n\t\tmulti: true\n\t}\n]\n```\n\n2. Implement ControlValueAccessor interface\n```ts\ninterface ControlValueAccessor {\n\twriteValue(obj: any): void\n\tregisterOnChange(fn: any): void\n\tregisterOnTouched(fn: any): void\n\tsetDisabledState(isDisabled: boolean)?: void\n}\n```\n\n\n| Function  | Description |\n| ------------- | ------------- |\n| registerOnChange  | Register a function to tell Angular when the value of the input changes |\n| registerOnTouched  | Register a function to tell Angular when the value was touched |\n| writeValue  | tell Angular how to Write a value to the input |\n\nSample implementation:\n```ts\n\n@Component({\n  selector: 'app-text-area',\n  templateUrl: './text-area.component.html',\n  styleUrls: ['./text-area.component.less'],\n  providers: [\n    {\n      provide: NG_VALUE_ACCESSOR,\n      useExisting: forwardRef(() => TextAreaComponent),\n      multi: true\n    }\n  ]\n})\nexport class TextAreaComponent implements ControlValueAccessor, OnInit {\n  @Input() value: string;\n\n  private _onChange = (data: any) => { console.log('changed: ' + data); };\n  private _onTouched = (data?: any) => {console.log('touched: ' + data); };\n\n  ngOnInit(): void {\n    const self = this;\n  }\n\n  constructor() {}\n\n  writeValue(obj: any): void {\n    this.value = obj;\n  }\n\n  registerOnChange(fn) {\n    this._onChange = fn;\n  }\n\n  registerOnTouched(fn: any): void {\n    this._onTouched = fn;\n  }\n}\n\n```\n\n# Tests\n\n## Unit tests\n\n**Service**\n```ts\ndescribe('MyService', () => {\n\tlet service: MyService;\n\tbeforeEach(() => service = new MyService();\n\tit('#fetch should update data', () => {\n\t\tservice.fetchData();\n\t\texpect(service.data.length).toBe(4);\n\t\texpect(service.data[0].id).toBe(1);\n\t});\n});\n```\n\nFor async functions\n\n```ts\nit('#fetch should update data', (done: DoneFn) => {    \n\t// some code\n\tdone();  // we need 'done' to avoid test finishing before date was received\n\t// some code\n});\n```\n\nexample async test: \n```ts\nit('http client works', (done: DoneFn) => {\n    service.getUser().subscribe((data) => {\n      expect(data).toBe('test');\n      done();\n    });\n });\n```\n\n**Spy and stub**\n\nSpy:\n```ts\n// create spied object by copy getDataAsync from HttpService\nconst valueServiceSpy =\njasmine.createSpyObj('HttpService', ['getDataAsync']);\n```\nStub:\n```ts\nconst stubValue = of('StubValue');\nvalueServiceSpy.getDataAsync.and.returnValue(stubValue);\n```\n\n**TestBed**\nMock whole module/environment for unit tests\n\n```ts\nbeforeEach(() => {\n\tlet httpClientMock = TestBed.configureTestingModule({ providers: [{ provide: MyService, useValue: new MyService(httpClientMock)}] });\n});\n```\n\nThen use tested object (for example service) like this:\n\n```ts\nservice = TestBed.get(MyService);\n```\nwe can add schemas: [NO_ERRORS_SCHEMA]. This means that we don’t have to mock children component dependencies of this component as Angular won’t yell at us anymore for our lack of doing so.\n\n\n# Others\n\n## Http interceptor\nIntercepts and handles an HttpRequest or HttpResponse.\n\nClass:\n```ts\n@Injectable()\nexport class MyInterceptor implements HttpInterceptor {\n\n\tconstructor() { }\n\n\tintercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {\n\t\t// do sth (like check and throw error)\n\t\treturn next.handle(request); //if want continue\n\t}\n}\n\n```\n\nModule:\n```ts\n{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, multi: true },\n```\n\n## host\nRefer to host element/component\n\n\n| Value  | Description |\n| ------------- | ------------- |\n| :host(selector) { ... }  | to match attributes, classes on the host element and add styling to it |\n| :host-context(selector) { ... }  | to match elements, classes on parent components and add styling to it  |\n| :host ::ng-deep   | styling will be applied also to all child components |\n\n\n# Interview questions\n\n**When would you use the useFactory provider method?**\n\nWith useFactory we can use a factory at runtime to decide which kind of service we want to return if it got requested by any other class in our application or you need to parameterize the construction of a service\n\n```ts\nexport function sampleFactory() {\n  return new Service1();\n}\n\nexport class Service1 {}\n\n@Injectable({\n  providedIn: 'root',\n  useFactory: xyzFactory\n})\nexport class Service2 {}\n```\n\nService1 will be injected into another class\n\n**What is router-outlet**\n\nActs as a placeholder that Angular dynamically fills based on the current router state. Generally in place of <router-outlet> your main app component will be generated\n\t\n**How to declare global value?**\n\nUse InjectionToken\n\n**Which decorator lets you inject a service registered with an Injection Token?**\n\n@Inject\n\nfor example\n```ts\n @Inject(CONTROLS_GLOBAL_CONFIG) globalVlues: ControlsConfig\n```\n\n**How to mimick environment for components/services in tests?**\n\nUse TestBed. See [Unit tests](https://github.com/delprzemo/angular-cheatsheet#unit-tests \"Unit tests\")  \n\n**What is Resolve interface?**\n\nInterface that classes can implement to be a data provider for component while routing.\n\nexample:\n\n```ts\n@Injectable()\nclass UserResolver implements Resolve<User> {\n  constructor(private service: MySampleService) {}\n\n  resolve(\n    route: ActivatedRouteSnapshot,\n    state: RouterStateSnapshot\n  ): Observable<any> {\n    return this.service.fetchData(route.params.id);\n  }\n}\n\n@NgModule({\n  imports: [\n    RouterModule.forRoot([\n      {\n        path: 'user/:id',\n        component: UserComponent,\n        resolve: {\n          userData: UserResolver\n        }\n      }\n    ])\n  ],\n  providers: [UserResolver]\n})\n```\n\nWe can use it to pre-load data for a component before the component is displayed\n\n**How to begin validation after the user will enter a value and pause?**\n\nUse debounceTime, for example\n\n```ts\nthis.formCtrlSub = this.firstNameControl.valueChanges\n      .debounceTime(1000)\n      .subscribe(newValue => this.firstName = newValue);\n```\n\n**What is valueChanges in form control?**\n\nTo catch value changes and implement some logic in observable result. See example above\n\n**How to execute canActivate if any of child routes will change?**\n\nUse canActivateChild\n\n**What are compilation types in Angular?**\n\n| Type  | Description |\n| ------------- | ------------- |\n| AoT  | Ahead of time - compile full application / module when application was opened. Used mainly on production  |\n| JiT  | Just in time - compile specific element when it has been opened. Used mainly while programming  |\n| Ivy  | Since Angular 8 - engine based on concept Incremental DOM  |\n\n\n**What is ng-content in Angular?**\n\nSee [ng-content](https://github.com/delprzemo/angular-cheatsheet/blob/master/README.md#content-projection \"ng-content\") \n\n**How to create application with cutom prefix?**\n\n```\nng new app-name --prefix my-cutom-prefix\n```\n\n**What is module lazy loading?**\n\nInstead of loading all modules while app starts we can load particular module when needed.\n\n```ts\nconst routes: Routes = [\n  {\n    path: 'users',\n    loadChildren: () => import('./users/users.module').then(m => m.UserModule)\n  }\n```\n\nThis is usually used for big apps in order to improve performance\n\n**Why should we consider using ngIf instead of ngClass/ngStyle for hiding element?**\n\nngIf won't generate element when condition result is fale, so html will be lighter. ngClass/ngStyle will just hide element but it will be still existing in DOM\n\n**What is Done() function in tests?**\n\nWe need 'done' to avoid test finishing before date was received\nSee [done](https://github.com/delprzemo/angular-cheatsheet#unit-tests \"done\") \n\n**What \"import\", \"providers\" and \"declarations\" stand for in NgModule?**\n\n```ts\ndeclarations: [AppComponent], // components, pipes, directives\nimports: [BrowserModule, AppRoutingModule], // other modules\nproviders: [], // services\n```\nSee [Sample module](https://github.com/delprzemo/angular-cheatsheet#sample-module-with-comments \"Sample module\") \n\n**Explain the difference between Constructor and ngOnInit**\n\nConstructor is a method assigned to a class, so it is called when class object was initialized.\nngOnInit is part of Component life cycle and it is dependent on the current state of view initialization.\nConstructor is called before ngOnInit\n\n**What is a difference between ElementRef and TemplateRef?**\n\nElementRef is reference to particular element while TemplateRef can refer to whole ng-template\n\n```html\n<ng-template #test>\n   Test\n</ng-template>\n```\n\n```ts\nexport class SthComponent  { \n\t@ViewChild('msg')\n\tprivate testTempRef : TemplateRef<any>\n}\n```\n\n**Point all data biding ways for element**\n\n| Bindint type  | Example |\n| ------------- | ------------- |\n| Property binding  | [src]=\"this.src\"  |\n| Event binding  | (click)=\"this.doSth()\"  |\n| Two way data bidning  | [(ngModel)]=\"this.form.userName\"  |\n\n**How to handle ngModel property in custom component?**\n\nImplement ControlValueAccessor interface.\nSee [ngModel](https://github.com/delprzemo/angular-cheatsheet#ngmodel-in-custom-component \"ngModel\")  \n\n**What is differenct between default and onPush change detector?**\n\ndefault change detector will check bidnings in whole application component tree after event\nOnPush change detector informs Angular that our component biding is depend on input parameters. Moreover it won't check bindings in whole application but only in subtree where our component belongs. \n\n**Why is it better to use pure pipes instead of some functions in template view?**\n\nIf we want to calculate for example user age and show it on template then we can do it with function:\n\n```html\n{{this.getUserAge(user.birthDate)}}\n```\n\nBut it will be calculated every time when change detector is run, so it can affect on performance. \nInstead we can use pipe for that:\n\n```html\n{{user.birthDate | calculateAge}}\n```\n\nNow age calculation won't be performed so many times. \n\n**How to detect change for any @Input property?**\n\nUse ngOnChanges hook\n\n```ts\nngOnChanges(values) {\n  // logic here\n}\n```\n\n**How to detect change for specific @Input in component?**\n\nUse 'set' accessor\n\n```ts\n@Input() set name(value) {\n  // some logic here\n}\n```\n"
  }
]