Posts

A type safe way of creating Angular ReactiveForms and FormGroups

If, like myself, you prefer as many of your coding mistakes to be identified at compile time as possible then you might like the following example. The FormBuilder in Angular expects us to identify our FormControls with a string name. If ever the API of your server changes then of course the names of those controls will also need to change. So, rather than using magic strings when building a FormGroup I wrote this small utility class for building them against a strongly typed class by using lambda expressions. This routine uses a routine I blogged about recently  ( Get lambda expression as a string) Take the following interface as an example of something we wish to edit in a ReactiveForm. interface Address { line1: string; line2: string; city: string; } The code to build the form would look like this this.form = this.expressionFormBuilder .createFormGroup<Address>() .addFormControl(x => x.line1) .addFormControl(x => x.line2) .addFormControl(x

Failed to execute 'send' on 'XMLHttpRequest': Failed to load ng:///DynamicTestModule - Solved (Angular testing)

If when you run your tests you see an error similar to this Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'ng:///DynamicTestModule/xxxxxxComponent_Host.ngfactory.js It means something in your component is throwing an exception and the test framework is returning a wrapped exception. To see the actual exception run ng test with -sm=false as a parameter ng test -sm=false This will not only stop your browser from freezing on that test, but will also give you the original error including line number.

Angular - How to create a data aware custom component

Introduction This blog will demonstrate how to create an Angular component that you are able to add [ngModel] [formControl] and [formControlName] attributes to your custom component, and have your component correct implement the features required to work with Angular forms. Setting up the ngModule First add FormsModule and ReactiveFormsModule to your main NgModule's import declaration import { FormsModule, ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } Creating the custom component's template Note: If you have installed @angular/cli using npm you can type ng g component /components/custom-input in a command prompt to create the component + template + test cases. Next create a new component with the following html template My custom input <input (

TypeScript - A polyfill to extend the Object class to add a values property to complement the keys property

I expect you've used Object.keys at some point. Here is how to extend the Object class to add a values property. This kind of thing is useful when you have a lookup of keys where all of the values are the same type, such as the following object you'd expect to see in a Redux app. { "gb": { code: "gb", name: "Great Britain" }, "us": { code: "us", name: "United States" } } The code interface ObjectConstructor { values<T>(source: any): T[]; } /** * Extends the Object class to convert a name:value object to an array of value * @param source * @returns {T[]} */ Object.values = function<T>(source: any): T[] { const result = Object.keys(source) .map(x => source[x]); return result; }

TypeScript - Get a Lambda expression as a string

One of the things I really like about C# is the ability to convert a lambda into a string. It's useful for doing all kinds of things, especially when you are calling a 3rd party library's method that expects a string identifying a member of an object. I saw this was lacking in TypeScript, which was a pain because I wanted to make various parts of my Angular application more compile-time resilient to changes in the server's API model. Using the following code it is possible to take a call like this someObject.doSomething<Person>(x => x.firstName) From there we can get the name of the property referenced in the lamba expression. In fact it will return the entire path after the "x." abstract class Expression { private static readonly pathExtractor = new RegExp('return (.*);'); public static path<T>(name: (t: T) => any) { const match = Expression.pathExtractor.exec(name + ''); if (match == null) { throw new

Angular - How to create composite controls that work with formGroup/formGroupName and ReactiveForms

This blog post will show you how to create composite controls in AngularX that allow you to reuse them across your application using the formGroupName directive to data-bind them. We'll start off with a very basic component that uses a reactive form to edit a person and their address. Editing a person's name and address import {Component, OnInit} from '@angular/core'; import {FormBuilder, FormGroup} from '@angular/forms'; @Component({ selector: 'app-root', template: './app.component.html', }) export class AppComponent implements OnInit { public form: FormGroup; constructor(private formBuilder: FormBuilder) {} ngOnInit(): void { this.form = this.formBuilder.group({ name: 'Person\'s name', address_line1: 'Address line 1', address_line2: 'Address line 2', }); } } <form novalidate [formGroup]="form"> <div> Name <input formControlName="nam

Redux sub-reducer pattern for complex / nested data structures

Image
I love the idea of the Redux pattern, the way all reducers are pure and predictable. I love the way they are effectively listeners that act on event notifications received from a central dispatcher, and I really like the way the whole approach simplifies the application and makes code in my Angular app's components only concerned with view related concerns rather than business logic. However, what I am not a big fan of is the normalised data approach. I've seen it recommended so many times for use with the Redux approach. You essentially have any object (read "row from table on server") in memory once and then everywhere else you hold a reference to the locally stored record/object by its unique ID. So, a view state you receive that looks like this [ { "id": "Emp1024", "name": "Peter Morris", "address": { "id": "123", "street": "xxx" } }, { "id": "Emp4096&qu