wonderful world
wonderful world

Reputation: 11599

What does the Resolver in ComponentFactoryResolver do?

Too many concerns in a class to create (Factory) and resolve (Resolver). What is the purpose of ComponentFactoryResolver in Angular2 and what it does?

Upvotes: 1

Views: 672

Answers (1)

Oliver Cooke
Oliver Cooke

Reputation: 1059

You can use it for the creation of dynamic components, it is specifically used for.

 Used to get the factory of the component we want to inject

When you pass your component name into the factory it returns the corresponding factory for the component defined in the entryComponents section of the page.

For example if you have a dashboard that contain a series of different graphs, you may want to display the same data using a different graph ie Line, Bar...

You an use a DynamicComponent to inject the component in, such as a BarChartComponent or a LineGraphComponent depending on what you want.

This factory is used to resolve that component.

object-to-pass-in.ts

public standard: any =
{
    Component: LineGraphComponent,
    Inputs: {
        GraphData: {
            //...graph data
        }
    }
};

dynamic.component.ts

import { Component, Input, ViewContainerRef, ViewChild, ReflectiveInjector, ComponentFactoryResolver } from "@angular/core";
import { BarChartComponent } from "./barchart.component";
import { LineGraphComponent } from "./linegraph.component";

@Component({
    selector: "hfa-dynamic-search",
    entryComponents: [BarChartComponent , LineGraphComponent],
    templateUrl: "app/app.component.html",
    styleUrls: ["app/app.component.css"]
})
export calss DynamicComponent {

    @ViewChild("dynamicComponent", { read: ViewContainerRef }) protected dynamicComponent: ViewContainerRef;

    @Input()
    set componentData(data: any) {
        ...
        //Creates a factory out of the passed in component name
        let factory = this.resolver.resolveComponentFactory(data.Component);

        //Creates the component out of the factory with the input values we want to inject
        let component = factory.create(injector);

        //Inserts it into the view
        this.dynamicComponent.insert(component.hostView);
        ...
    }

    constructor(private resolver: ComponentFactoryResolver) { }
}

dynamic.component.html

<div #dynamicComponent></div>

Credit to a great blog post on how its implemented here

Hope that helps.

Upvotes: 1

Related Questions