If you’ve ever tried to put a placeholder attribute on a date input like so :

<input type="text" name="myDateField" placeholder="Enter the date here" />

You know it doesn’t work.

Instead what you end up with is the field being pre-populated with “dd/MM/yyyy” which is incredibly annoying! But there is actually a way to get the placeholder working by instead making the input function as a textbox until clicked, and then quickly swapping it to act like a date input.

First we need to change out input to be of type “text” like so :

<input type="text" name="myDateField" placeholder="Enter the date here" />

We are now going to create a new directive. In my case I named it DynamicDateInputDirective. The contents of which is :

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: 'input[dynamic-date-input]'
})
export class DynamicDateInputDirective {

  private element : ElementRef;

  constructor(element : ElementRef) { 
    this.element = element;
  }

  @HostListener('focus')
  handleFocus()
  {
    this.element.nativeElement.type = 'date';
  }

  
  @HostListener('blur')
  handleBlur()
  {
    if(this.element.nativeElement.value == "")
    {
      this.element.nativeElement.type = 'text';
    }
  }

}

What does this do?

  • We use the HostListener to bind to the focus event, on focus, we ensure that the field is of type “date”.
  • We then use the HostListener to bind to the blur event (So focus is moving away from the field). We check to see if the field is empty, if it is, return it to the “text” type. What this means is if someone clicks into the field but doesn’t enter anything and moves away, we keep our placeholder.

You can then add the directive to your text input :

<input type="text" name="myDateField" dynamic-date-input placeholder="Enter the date here" />

Not using Angular? The paradigm is the same if you are using React, jQuery or even Vanilla JS. On focus you need to change your text type to date, and then on blur you need to do the reverse (Remembering to only do it if the value is empty).

Every “control” in Angular has EventEmitters called statusChanges  and valueChanges . The former is whether a control is “valid” so will emit an event every time a control changes from invalid to valid or vice versa. valueChanges  is when the actual control’s “value” changes. In most cases this is going to be a form element so it will be the value of the textbox, checkbox, input etc. In a custom component’s case, if you implement ControlValueAccessor, then it’s going to be the “value” of your control as bound by the ngModel.

In anycase, I came across an interesting scenario in which I needed to “subscribe” to changes when a control was “touched”. To my surprise, there is currently no event that is emitted when a control is touched – or when it’s status of pristine/dirty is changed. It’s actually pretty bonkers because typically when showing error messages on a form in Angular, you will make liberal use of the “IsDirty” or “IsTouched” properties. So being able to “listen” for them seems pretty important. Ugh. Time to Monkey Patch.

What Is Monkey Patching?

Monkey Patching is a technique to change or modify the default behaviour of code at runtime when you don’t have access to the original code. In our case, we want to be “notified” when “markAsTouched” is called. To do so, we need to modify the actual method of “markAsTouched” to emit an event/run a custom piece of code *as well* as do it’s regular method.

If you are interested in reading more about Monkey Patching, there is a great article (In Javascript no less) on the subject here : audero.it/blog/2016/12/05/monkey-patching-javascript/

Monkey Patching MaskAsTouched/Pristine/Dirty

To make this work, the first thing you need is a reference to the *control* that you are trying to listen for the touched event on. This could be done using ViewChild if you are looking for a child control on the page. To get the “self” control (e.g. in a custom component), a common pattern is to modify your constructor to inject in the “Injector” class which you can use to get the NGControl instance of yourself. You need to do this in the ngAfterViewInit method.

constructor(private injector: Injector) { }

ngAfterViewInit()
{
  let ngControl : NgControl = this.injector.get(NgControl, null);
}

OK so we have the reference to the control. Time to patch things up!

let self = this;
let originalMethod = this.control.markAsTouched;
this.control.markAsTouched = function () {
  originalMethod.apply(this, arguments);
  //Extra code needed here. 
}

Let’s walk through this code.

  • First we get a reference to ourselves. This isn’t necessarily required, but it’s highly likely we may want to refer to local variables/properties, and inside our function we lose scope of “this”.
  • We store the original “markAsTouched” method from our control reference. This line will obviously differ slightly on how you are referencing the control you want to patch.
  • We then set the markAsTouched method to a new function, that then itself runs the original method (e.g. Run Angular’s standard “markAsTouched”).
  • We can then run our extra code as required. This may be to raise an event on an EventEmitter, set another variable, run a method, whatever!

In my case, when my custom component was touched, I wanted to then manually “touch” another child component. So my full code looked like :

let self = this;
let originalMethod = this.control.markAsTouched;
this.control.markAsTouched = function () {
  originalMethod.apply(this, arguments);
  self.bankDetailsForm.form.markAllAsTouched();
}

We can use this method to do the same for markAsPristine, markAsDirty, or actually any other method that Angular for unknown reasons doesn’t give us an event for.

Beware Infinite Loops

I would suggest when you do your first monkey patch, be liberal with your console.log statements. I found pretty quickly when trying to touch another control from within my monkey patched markAsTouched method, that I created an infinite chain of touching. It’s super easy to do so you’ll need to be extra careful.

When it comes to running “one off” startup methods when your Angular Application starts, everyone will tell you to use the “APP_INITIALIZER” token. That’s all well and good to be told that, but when you actually check the documentation, it’s a little sparse…

Admittedly there is a bit more on the token scattered around in other documentation pieces, but they are surprisingly hard to find and again, typically only lightly touch on actual real world usage. So consider this a beginners guide on how to use APP_INITIALIZER in your own app.

The Basics

The first step is to create our startup function. For the purposes of this article, I’m going to create a simple function that itself, returns a function to run.

export function startmeup()
{
  return () => console.log('Started!');
}

It’s important that the function itself returns a function!

In our main module (typically AppModule), we want to add a provider to our NGModule decorator. For example :

@NgModule({
  declarations: [
  ],
  imports: [
  ],
  providers: [
    { provide : APP_INITIALIZER, multi : true, useFactory : startmeup}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Ignore the fact I don’t have any declarations, I’ve removed them so it doesn’t clutter things up. Now a couple of things to note here.

  • We are adding a provider with the key of APP_INITIALIZER
  • We are setting the “multi” flag to true as we may have multiple APP_INITIALIZER’s to run.
  • And finally we are telling it to use the startmeup method to create the method we want to run.

Running our application now, we should see a console message of “Started!” as soon as the page loads.

UseValue vs Use Factory

It may look strange for our startup method to itself return a method. It seems a bit silly to box things up like that. Why not just run the startup code itself? Well you can do that (With some caveats).

For example, we could change our startmeup function to look like so :

export function startmeup()
{
  console.log('Started!');
}

Then we can change our provider line to “useValue” instead of “useFactory”

{ provide : APP_INITIALIZER, multi : true, useValue : startmeup }

The main problem you run into with this method is that it’s much harder to use dependencies. We’ll talk about that a little later on. For now, just know you can do either but there are certainly pros and cons for each. Typically I find factories provide me the most versatility.

Inline Methods

It’s obviously worth noting that you don’t need to create an entirely new function variable/object, and you can instead do it all inline.

For the useValue route, you can use :

{ provide : APP_INITIALIZER, multi : true, useValue : () => { console.log('Started!'); }}

To do the same thing with factories does look a little messier because you need to return a method that returns a method… So the nesting can look a bit extreme but in general it looks like :

{ provide : APP_INITIALIZER, multi : true, useFactory : () => { return () => console.log('Started!'); }},

Using Dependencies

It’s possible, but unlikely, that your startup method can run on it’s own with no dependencies. But it’s probably a whole lot more likely that you are going to require either outside services of your own, or Angular’s own helper services. HttpClient for example.

You can inject these into your startup factories. Note that you cannot (easily) inject dependencies when using useValue. Your application won’t blow up, but your dependency will be undefined. There are ways around this but it’s the primary reason to stick with useFactory.

As an example of using dependencies, I can rewrite my startup factory like so :

export function startmeup(http : HttpClient)
{
  return () => 
  {
    console.log(http);
    console.log('Started!');
  }
}

And I can modify my provider line adding in the “deps” field :

{ provide : APP_INITIALIZER, multi : true, deps : [HttpClient], useFactory : startmeup}

This allows Angular’s built in DI to inject in HttpClient to my startup method which is extremely handy!

Calling Startup Methods Of Services

So, exporting functions all over the place is sort of rough. And it’s pretty likely that we want to bootstrap an actual service (Maybe to reach out and grab configuration values etc). To do that, we can create a class that holds our startmeup factory. We also need to mark it as Injectable.

@Injectable({
  providedIn: 'root'
})
export class StartupClass
{
  constructor(private http:HttpClient)
  {

  }

  startmeup()
  {
    return () => 
    {
      console.log(this.http);
      console.log('Started!');
    }
  }
}

When adding our provider line, we now instead set our dependency to be the StartupClass (The additional dependency of HttpClient will be resolved behind the scenes when requesting the StartupClass). We still call useFactory as we still have to tell it which particular method we want to run on startup.

{ provide : APP_INITIALIZER, multi : true, deps : [StartupClass], useFactory : (startupClass : StartupClass) => startupClass.startmeup()}

Note that our method is actually still returning a function itself. This can be a bit off putting to read in this way so we can change it to instead simply run it’s startup calls :

startmeup()
{
  console.log(this.http);
  console.log('Started!');
}

And then modify the provider line to instead create a factory in of itself :

{ provide : APP_INITIALIZER, multi : true, deps : [StartupClass], useFactory : (startupClass : StartupClass) => () => startupClass.startmeup()}

Notice the additional () to create a method within the useFactory line.

Using Promises

A pretty common scenario for startup methods is reaching for configuration values. That could be from a file, local storage, a cookie etc. And it’s highly possible that these methods are async in nature. As an example below, I’ve modified my startup method to read a settings file.

startmeup()
{
    this.http.get('/assets/config/app-settings.json').subscribe(async x => 
    {
      await new Promise(resolve => setTimeout(resolve, 5000));
      console.log('Configuration loaded');
    });
}

Note that the await promise line is simply to make it “seem” like it’s taking a long time to complete it’s job. e.g. It’s a slow startup task. In a real world example this wouldn’t be there.

Let’s also go to our main app component and write an NgOnInit method that simple writes to the console log.

export class AppComponent implements OnInit{
  ngOnInit(){
    console.log('On Init');
  }
}

Now let’s pause for a second and think. If we run our app right now, what will be written to the console first? The “Configuration loaded” message or the “On Init” message. Well logic would tell us that surely our message that our configuration loaded will run first because we’ve told Angular that the startmeup method should be loaded before everything else.

Well that is wrong.

The problem is that the http get method returns an observable to tell us when it’s complete. And we aren’t waiting for that to finish at all.

The general pattern is to use promises and return that promise to the APP_INITIALIZER. So as an example :

startmeup()
{
    return this.http.get('/assets/config/app-settings.json').toPromise().then(async x => 
    {
      await new Promise(resolve => setTimeout(resolve, 5000));
      console.log('Configuration loaded');
    });
}

Here we are returning a promise from our method. The App Initializer will actually wait until this promise is resolved before continuing on. If we refresh our page now, we will notice that not only does the “On Init” message come after the “Configuration loaded” message. But the page itself is blank for 5 seconds (Because of our fake sleep to emulate a long http call) because all progress is halted until startup is complete.

This may sound bogus to halt an application like this. But the general idea is that the “majority” of work from your Angular application would not actually be able to take place until the startup method is resolved. For example if you are using telemetry like New Relic, Raygun, Application Insights etc. You really should have the token loaded and App Insights running before attempting to do other work. Otherwise if your application crashes, there is now a race condition as to whether you have all the necessary information to log the error or not.

Usage Outside Of Single Page Apps

As we saw above, the use of APP_INITIALIZER essentially halts the loading of a page until complete. In a true Single Page App (SPA), this is fine because it’s only really going to happen once on the initial load. If you are making use of Angular’s router for instance, then the App Initializer won’t be called again until a proper browser refresh occurs.

Obviously this isn’t the case if you are doing full page reloads. Every page load will re-load the angular app, and therefore kick off the startup process again. Be wary of using the APP_INITIALIZER token in these situations as it can severely slow down your application on every single page load.

I get this little error almost daily when working in Angular (Particularly in VS Code).

Type 'EventEmitter' is not generic.

The first time I got the issue, it drove me mad as I was copy and pasting code from another file where it was working just fine, yet in my new code file everything was blowing up.

As it turns out, NodeJS has it’s own version of “EventEmitter” that is not generic. When using VS Code or other IDE’s that have auto completion, they will sometimes pick this EventEmitter to import rather than the one from Angular. The way to check is to see what your import statement looks like. It should be coming from @angular/core :

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

In my (broken) case, it was :

import { EventEmitter } from 'events';

In actuality, there are a couple of EventEmitter objects. For example another half broken example would be :

import { EventEmitter } from 'stream';

So just check exactly where you are importing EventEmitter from to get around this pesky error!

When I first picked up Angular many years ago, one of the more frustrating aspects was that on using the router to navigate to another page, the scroll position was kept. This meant you were taken to the new page, but you would be scrolled halfway down the page (Or often right at the bottom if you were filling out a form).

Back then, you had all sorts of crazy fixes involving listening for router events, or maybe even manually scrolling the page. So recently when I ran into the issue on a new project I hoped things had changed. And they have, sort of. I mean, the issue is still there but there is a slightly more elegant fix.

When registering your router module (Typically a new Angular project created using the CLI will have an app-routing.module.ts), you can now edit your import as follows  :

RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})

In future versions of Angular, it’s hoped that this will become the default (Certainly there would be far more use cases of scrolling to the top over keeping the same position), but as of writing you still manually need to add the scrollPositionRestoration param.

Note that this was introduced sometime in Angular 6, for earlier versions (Which hopefully you aren’t creating new projects on), you will still need to do the old school subscribe method. To do this, you need to modify your main component (Often your AppComponent) to subscribe to the router event of NavigationEnd and then call scroll.

export class AppComponent implements OnInit  {
  private router : Router;

  constructor (router : Router)
  {
    this.router = router;
  }

  ngOnInit() {
    this.router.events.subscribe(x => {
      if(x instanceof NavigationEnd)
      {
        window.scrollTo(0, 0);
      }
    });
  }
}

Again this is required only if you are running a version of Angular before 6!

As part of a recent project, I was asked to limit the type of characters that can be input into a text field. I had a quick search around but every single time I thought I had found a solution, it was some form of using the pattern attribute to simply show if invalid characters had been input, but it didn’t actually stop the user from typing them in the first place.

Now, I know that sometimes this can be a bit of an anti-pattern as a limiting the users input like this can be frustrating when you don’t show any warning or validation message, but there are some valid use cases.

The Directive Code

Below is the actual directive which you can add into your Angular project. In my case, I’m developing in Angular 8, but this should work in any modern Angular version.

import { Directive, ElementRef, Input, HostListener } from '@angular/core';

@Directive({
  selector: '[inputrestriction]'
})
export class InputRestrictionDirective {
  @Input('inputrestriction') InputRestriction : string;

  private element : ElementRef;

  constructor(element : ElementRef) {
    this.element = element;
  }

  @HostListener('keypress', ['$event'])
  handleKeyPress(event : KeyboardEvent)
  {
    var regex = new RegExp(this.InputRestriction);
    var str = String.fromCharCode(!event.charCode ? event.which : event.charCode);
    if (regex.test(str)) {
        return true;
    }

    event.preventDefault();
    return false;
  }

}

A quick rundown of the code :

  • I’m using the selector of “inputrestriction” and I’ve made the input variable itself be called the same. Change as you require.
  • The input string takes a regex pattern to match on *allowed* characters.
  • I’m using the host listener to listen for a key press and deciding to allow it or not.

Usage Examples

We can then crack on with some really simple use cases such as letters only :

<input inputrestriction="[a-zA-Z]" type="text" />

Or numbers only :

<input inputrestriction="[0-9]" type="text" />