2017-08-12

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 
  (blur)="blurred()" 
  (focus)="focused()" 
  [(ngModel)]="value" />

The custom component's class code

First you need to import a few references
import { Component, forwardRef, Input } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
What these identifiers do:
  • NG_VALUE_ACCESSOR: A marker in the component's providers declaration to indicate that the new component implements ControlValueAccessor
  • ControlValueAccessor: The interface that needs to be implemented in order to support data-binding through [formControl] and [formControlName]
Now update the component's @Component declaration and add providers, and update the selector.
@Component({
  selector: '[formControl] custom-input, [formControlName] custom-input',
  templateUrl: './custom-input.component.html',
  styleUrls: ['./custom-input.component.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => CustomInputComponent),
      multi: true
    }
  ]
})

And finally, the component's class code

export class CustomInputComponent implements ControlValueAccessor {
  private _value: any;

  private hasHadFocus = false;
  private hasNotifiedTouched = false;
  private propagateChange: any = () => {};
  private propogateTouched: any = () => {};

  public get value(): any {
    return this._value;
  }

  @Input('value')
  public set value(value: any) {
    this._value = value;
    this.propagateChange(value);
  }

  /**
   * Called when input (focus) is triggered
   */
  public focused() {
    this.hasHadFocus = true;
  }

  /**
   * Called when input (blur) is triggered
   */
  public blurred() {
    if (this.hasHadFocus && !this.hasNotifiedTouched) {
      this.hasNotifiedTouched = true;
      this.propogateTouched();
    }
  }

  /**
   * Called when a new value is set via code
   * @param obj
   */
  writeValue(value: any): void {
    this.value = value;
  }

  /**
   * Register Angular's call back to execute when our value changes
   * @param fn
   */
  registerOnChange(fn: any): void {
    this.propagateChange = fn;
  }

  /**
   * Register Angular's call back to execute when our value is first touched
   * @param fn
   */
  registerOnTouched(fn: any): void {
    this.propogateTouched = fn;
  }
}

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

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 Error('The function does not contain a statement matching \'return variableName;\'');
    }
    return match[1].split('.').splice(1).join('.');
  }
}

Example

The following example will show the string 'country.code'
interface Address {
    line1: string;
    country: {
        code: string;
        name: string;
    }
}

const result = Expression.path
(x => x.country.code); alert('Result is ' + result);

2017-08-10

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="name"/>
  </div>
  <div>
    Address line 1 <input formControlName="address_line1"/>
  </div>
  <div>
    Address line 2 <input formControlName="address_line2"/>
  </div>
</form>

Making the address editor a reusable component

At some point it becomes obvious that Address is a pattern that will pop up quite often throughout our application, so we create a directive that will render the inputs wherever we need them.

First, change the formBuilder code in the parent component so that address is a nested group.

  ngOnInit(): void {
    this.form = this.formBuilder.group({
      name: 'Person\'s name',
      address: this.formBuilder.group({
        line1: 'Address line 1',
        line2: 'Address line 2',
      })
    });
  }

Then we need to change the html template in the parent component so that it uses a new composite control instead of embedding the html input controls directly. To pass the context to our composite child control we need to use the formGroupName attribute.

<form novalidate [formGroup]="form">
  <div>
    Name <input formControlName="name"/>
  </div>
  <address-editor formGroupName="address"></address-editor>
</form>

The html of the edit-address component is quite simple. As with the main component we will need a [formGroup] attribute to give our inner inputs a context to data bind to.

<div [formGroup]="addressFormGroup">
  <div>
    Address line 1 <input formControlName="line1"/>
  </div>
  <div>
    Address line 2 <input formControlName="line2"/>
  </div>
</div>

Finally we need our edit-address component to provide the addressFormGroup property the view requires for its [formGroup] directive. To do this we need a ControlContainer reference, which is passed in via Angular's dependency injection feature. After that we can use it's control property to get the FormGroup specified by the parent view. This must be done in the ngOnInit method, as ControlContainer.control is null at the point the embedded component's constructor is executed.

import {Component, OnInit} from '@angular/core';
import {ControlContainer, FormGroup} from '@angular/forms';

@Component({
  // Ensure we either have a [formGroup] or [formGroupName] with our address-editor tag
  selector: '[formGroup] address-editor,[formGroupName] address-editor',
  templateUrl: './address-editor.component.html'
})
export class AddressEditorComponent implements OnInit {
  public addressFormGroup: FormGroup;

  // Let Angular inject the control container
  constructor(private controlContainer: ControlContainer) { }

  ngOnInit() {
    // Set our addressFormGroup property to the parent control
    // (i.e. FormGroup) that was passed to us, so that our
    // view can data bind to it
    this.addressFormGroup = this.controlContainer.control;
  }
}

Summary

That's all there is to it! Writing a component that edits a composite data structure is even easier than writing a custom control for editing a single piece of data (FormControl) - which I will probably describe in another blog entry.