Using SharePoint Framework (SPFx) with Angular 2

Update: This approach, is not AOT ready, please see https://winsmarts.com/angular-elements-and-spfx-a2a5fa32bb21 for a better way out.

First of all, I hate having to use the term “Angular 2” because the team is calling it just Angular. But hey, I need to differentiate it from Angular 1 .. so .. :-)

Anyway, in SharePoint Framework, you create client web parts, perhaps later down the road, you’ll also create more UX elements. But the challenge is, when you drop your widget on a page, and you are using a certain selector (say myApp, or app-root), there is a chance that you may conflict with an existing ID already on the page. And that will pretty much break your code.

Luckily there is a workaround. You can create a component on the fly, and define it’s selector to be unique. The easiest way to do that is by appending the component’s selector with “this.context.instanceId”, instanceId is a GUID that is unique to the instance of the ClientWebPart.

So now that you can create the selector on the fly, the next thing you need to do is add that selector to the DOM dynamically also. This can be done in the “render” method using code like this,

this.domElement.innerHTML = `<ng2-webpart-${this.context.instanceId} />`;

And then there is the issue of timing! So you this innerHTML must be added to the code before the module is created and the component is hydrated as a part of this module. So you need to craft up the module dynamically.

All of this can be seen in a working example at https://github.com/SharePoint/sp-dev-fx-webparts/tree/master/samples/angular2-prototype

Now, I like that working example! And I like the approach it has taken. I do see numerous downsides though. For instance, how do you leverage routes, or lazy/eager loading. How do you bake in AOT?

So let me just say that this design pattern is a great start! But it needs to go a lot further. And I’ll be writing about it shortly. LOL.