Gradual migration of .net mvc application to Angular 2 - Part 2

Ok, so it wasn't quite as simple as I thought. Although it was possible as mentioned in the previous post to boot an Angular 2 root component within each individual page of an existing .Net MVC app there were two problems:

  1.  On each MVC page the Angular 2 root component needs to have a different child component in order to instantiate just the component for the given page - so this component needs to be dynamically set at run time.
  2. It is not possible to bind an attribute to the Angular 2 root component in order to use @import to pass in the child component.
Point number 2 was easily fixed by getting the raw element attribute on the root app component and binding this to the input of a nested <dynamic-component>.

Then the new dynamic component can take the name of the component passed in and insert this into its own template

This component needs to import all of the possible components that could be passed in as top level components (I have just included a couple of examples of a user-list and site-list component). I add these to a lookup in order to avoid a nasty switch statement in the DynamicComponent class.

This component sets up a view child at the #container div, and then uses ComponentFactoryResolver to create and insert the component at this point.

One important thing to note, is that any top level components that you are going to pass in this way need to be added to the entryComponents: setting of the module to which they belong. This is because these components will be loaded imperatively rather than declarativley.

In each MVC page the root component can be added and the first child component passed in as <app componentName="user-list"></app>


  1. Thank you so much for this post !!! Right now I'm trying to do this with an app. You don't have any example/sample with this working that you can share with me please ? Thanks for your time!!

    Best regards, Miguel

    1. Hi Miguel - sorry I don't have any working examples of this to share - I did this initial prototyping, but company decided not to proceed with the upgrade and I was pulled onto another project.


Post a Comment