{{announcement.body}}
{{announcement.title}}

Angular Survival Kit

DZone 's Guide to

Angular Survival Kit

Is Angular killing you? Check out this great Angular survival kit that runs you through TypeScript and HTML code for various programming issues.

· Web Dev Zone ·
Free Resource
https://stackoverflow.com/questions/35435042/how-can-i-define-an-array-of-objects-in-typescript

https://stackoverflow.com/questions/29382389/defining-array-with-multiple-types-in-typescript

https://basarat.gitbooks.io/typescript/docs/types/generics.html

Angular SwitchCase

<!div *ngFor="let id of ids">Id is {{id}}
  <!div ngSwitch="{{id%2}}">
  <!div *ngSwitchCase="'0'" [ngClass]="'one'">I am Even.<!/div>
  <!div *ngSwitchCase="'1'" [ngClass]="'two'">I am Odd.<!/div>
  <!div *ngSwitchDefault>Nothing Found. <!/div>

<!/div> <!/div>

Testing Localstorage

  spyOn(localStorage.__proto__, 'removeItem');
  component.removeToken();
  expect(localStorage.__proto__.removeItem).toHaveBeenCalledTimes(2);

Testing Form Controls


it('submitting a form emits a user', () => {
    expect(component.form.valid).toBeFalsy();

    component.form.controls['email'].setValue("test@test.com");
    component.form.controls['phone'].setValue("111222333");
    expect(component.form.valid).toBeTruthy();

    let user: User;
    // Subscribe to the Observable and store the user in a local variable.
    component.loggedIn.subscribe((value) => user = value);

    // Trigger the login function
    component.submit();

    // Now we can check to make sure the emitted value is correct
    expect(user.email).toBe("test@test.com");
    expect(user.phone).toBe("111222333");
  });

Testing Util Class (Non-Static methods)

import { countries } from './countries';
import { Util } from './util';

let testClass: Util = null;
describe('Util Tests', () => {
  beforeEach(() => {
    testClass = new Util();
  });

  it('should ensure getCountries is based on countries file', () => {
    const actual = testClass.getCountries;
    expect(actual[0].id).toEqual(countries[0].id);
  });
});

import { countries } from './countries';
export class Util {

  public countries: any[] = countries;
  public getProducts() {
    return this.countries;
  }
}

Force Change Detection

import { ChangeDetectorRef } from '@angular/core';

constructor(
  private ref: ChangeDetectorRef
) {}

this.ref.markForCheck();
this.ref.detectChanges();

Check if Already Selected Item Was Clicked

ts:
public onUpdate(event, index) {
  const preventAction = event
    .target.classList.contains('selected');
  if(!preventAction) {
    // handle the event that got fired!
  }
}
tpl:
(click)="onUpdate($event, i)"

jQuery:
$(document).ready(function() {
    $("a").click(function(event) {
        console.log(event.target.class);
    });
});

Routing and Dynamic Form Controls Setup

constructor(private router: Router) {}

this.arryUsers.forEach(user=&gt;{
  this.userForm.addControl(user.id , control);
});

goHome() {
    this.router.navigate(['']);
}

<!-- *ngFor="let item of items; let i = index" -->

Form State

onChanges(): void {
  this.myForm.valueChanges.subscribe(val => {
    console.log(val);
  });
}

onSubmit() {
  if (this.myform.valid) {
    console.log("Form Submitted!");
  }
}
tpl:
{{myform.value | json}}

Promises Basic

// Promises Basic
var p1 = Promise.resolve("calling next");
p1.then((res)=>console.log(res));

JSON Filters

// lookup attributes for a value
vendors = [{
      Name: 'Apple',
      ID: 'APL'
    },
    {
      Name: 'Microsoft',
      ID: 'MST'
    }];

# solution 1 ES6 Arrow
vendors.filter(e => e.Name === 'Microsoft');

# solution 2 only till 1st result is found
vendors.find(item => {
    return item.Name === 'Microsoft';
});

Test DOM Elements With Jasmine

// Jasmine query selector by id
de = fixture.debugElement.query(by.css('#main-container'));

import { TestBed, async, ComponentFixture } from '@angular/core/testing';

describe('', () => {
  let fixture: ComponentFixture;
  let component: TestComponent;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ ],
      declarations: [ TestComponent ],
      providers[  ]
    }).compileComponents().then(() => {
      fixture = TestBed.createComponent(TestComponent);
      component = fixture.componentInsance;
    });
  }));
});

it('should', async(() => {
  spyOn(component, 'onEditButtonClick');

  let button = fixture.debugElement.nativeElement.querySelector('button');
  button.click();

  fixture.whenStable().then(() => {
    expect(component.onEditButtonClick).toHaveBeenCalled();
  })
}));

OR

it('should', fakeAsync( () => {
    fixture.detectChanges();
    spyOn(componentInstance, 'method name'); //method attached to the click.
    let btn = fixture.debugElement.query(By.css('button'));
    btn.triggerEventHandler('click', null);
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(componentInstance.methodName).toHaveBeenCalled();
}));

TypeScript Getters

these shorthands really help to get rid of long getters that you have to write in order to access a from property.

export class SignupFormComponent {
  get email() {
    return this.signupForm.get('email');
  }

  get password() {
    return this.signupForm.get('password');
  }

  get terms() {
    return this.signupForm.get('terms');
  }
}

Re-Render Child Component

Sometimes updating @input doesn't guarantee a re-render of child components. Here is an approach to resolve it.

export class ChildComponent implements OnChanges {
  @Input() data: Data;
  @ViewChild('childComp') childComp: ElementRef;

  ngOnChanges(changes: SimpleChanges) {
    this.updateData();
  }
}<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

Proxy Conf in Angular 2+

in case, if we run mock apis on http://localhost:3000/api & want all calls to http://localhost:4200/api reach the first (mock) server.

DOC - https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md

Serve Angular on XAMPP (Apache) server

change in my root directory index.html file which is:

Now build the app:

/> ng build --prod
copy dist folder and paste it in my xampp htdocs folder and access the site using:
localhost:8080/dist/

Ref:

Topics:
web dev ,angular ,typescript ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}