What is a factory in Angular

What exactly are factories in Angular(2+)?

Factory is one of the design patterns mentioned by Gang of Four (Basically they wrote a book on the design patterns they discovered).

Design Patterns help programmers solve common development tasks in a specific way.

And in this case, the Factory pattern helps in instantiation and creation of Objects.

It is also known as the Virtual Constructor.


Think of it, like this:

Say you are making a 2D shooter game, and you have to shoot bullets out of barrels.

Instead of instantiating bullets like new Bullet(), every time trigger is pulled, you can use a factory to create bullets, i.e. WeaponsFactory.createInstance(BulletTypes.AK47_BULLET).

It becomes highly scalable, since all you have to do is change the enum and the factory will make it for you.

You won't have to manually instantiate it.


That is what angular does, it automatically creates factory of all the components. Which makes its job easier.

Are there scenarios that a developer benefits form knowing how they work?

You don't have to know the inner workings of a Factory to use Angular, but it's useful for creating components dynamically!

e.g. A lot of *ngIf, or *ngSwitchCase can be replaced by a simple dynamic generation of components

Components can be created dynamically like this:

createComponent(type) {
  this.container.clear();
  const factory: ComponentFactory = this.resolver.resolveComponentFactory(AlertComponent);
  this.componentRef: ComponentRef = this.container.createComponent(factory);
}

Reference for understanding the above code: Dynamically Creating Components