Integrate Angular Elements with SharePoint Framework

In this article, we will explore how to create SharePoint Framework web part using Angular 6 framework.

Pre-Requisites

  • Setup development environment for SharePoint framework. See this link.
  • Basic knowledge of Angular Elements. See this link.
  • Visual Studio Code. Download here.

What are Angular Elements

Angular elements are Angular components packaged as custom elements, a web standard for defining new HTML elements in a framework-agnostic way. Read more here.

SharePoint Project

Considering all pre-requisites are met. Create a folder in your working directory where project will be created. (In my case i have created a folder “Demos” on my desktop.). Launch command prompt and navigate to the folder. Type below command and hit enter-

yo @microsoft/sharepoint

folder

This will start the creation of project and will prompt for few details (see below screenshot). Provide the details or accept the default values-

Project

It will take some time as it will install all the packages required for SharePoint project.

install

Once project is created successfully, below screen is displayed-

sucess

Type below command to open project in Visual Studio Code –

code .

In VS Code, project will look like this-

vscode

Note: – Keep the command prompt open.

Integrate  Angular with SharePoint

Lets update some of the files for Angular to work with SharePoint Framework.

package.json

This file includes list of all packages required for the project. Open package.json file, under dependencies add following packages –

"@angular/common": "^6.0.3",
"@angular/compiler": "^6.0.3",
"@angular/core": "^6.0.3",
"@angular/elements": "^6.0.3",
"@angular/platform-browser": "^6.0.3",
"@angular/platform-browser-dynamic": "^6.0.3",
"@webcomponents/custom-elements": "^1.1.1",
"core-js": "^2.5.7",
"rxjs": "^6.2.0",
"zone.js": "^0.8.26"

tsconfig.json

This is the TypeScript configuration file for the IDE. Open tsconfig.json file, add below line under “compilerOptions”-

"emitDecoratorMetadata": true,
New file should look like below-
{
   "compilerOptions": {
        "target": "es5",
        "forceConsistentCasingInFileNames": true,
        "module": "esnext",
        "moduleResolution": "node",
        "jsx": "react",
        "declaration": true,
        "sourceMap": true,
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "skipLibCheck": true,
        "typeRoots": [
            "./node_modules/@types",
            "./node_modules/@microsoft"
        ],
        "types": [
            "es6-promise",
            "webpack-env"
        ],
        "lib": [
            "es5",
            "dom",
            "es2015.collection"
        ]
   }
}
This is essential for Angular and it forces TypeScript to save type information as metadata. This helps the compiler to emit design-type information for decorated declarations. For decorators read this.

gulpfile.js

This file defines all the tasks for the project like compiling TypeScript files to JavaScript, bundle and minify JS/CSS files etc. We need to modify the build process. Open “gulpfile.js” file and add below code just above the “build.initialize” line-
const webpack = require('webpack');
const path = require('path');

build.configureWebpack.mergeConfig({
   additionalConfiguration: (generatedConfiguration) => {
      
      generatedConfiguration.plugins.push(new webpack.ContextReplacementPlugin(/\@angular(\\|\/)core(\\|\/)fesm5/, path.join(__dirname, './client')));
      
      return generatedConfiguration;
   }
});
New file should look like this-
gulpfile

Create Angular Component

Lets the create the component that will be rendered in SharePoint Framework. In Visual Studio Code, expand folder “src” -> “webparts” -> “myEvents” (this can be different based on name provided while creating the project) and create folder “app”.
Under “app” folder, create below files-
appfolder

app.module.ts

This file is the entry module for the Angular application. Below is the content in this file-
import { BrowserModule } from "@angular/platform-browser";
import { NgModule, Injector } from "@angular/core";
import { createCustomElement } from "@angular/elements";
import { AppComponent } from "./app.component";
import { HttpClientModule } from '@angular/common/http';

@NgModule({
      imports: [
         BrowserModule,
         HttpClientModule
      ],
      declarations: [
         AppComponent
      ],
      entryComponents: [
         AppComponent
      ],
      providers: []
})

export class AppModule {
     constructor(private injector: Injector) {}

     public ngDoBootstrap() {
         if(!customElements.get("my-app"))
         {

            const AppElement = createCustomElement(AppComponent, {injector : this.injector});
            customElements.define("my-app", AppElement);
         }
     }
}

app.component.ts

This is the component which will hold the html/data to be displayed. Here we are displaying message configured through property pane and URL of current site. Below is the content of this file-
import { Component, Input } from "@angular/core";

@Component({
   selector: "my-app",
   template: `
         This is Angular Elements SharePoint Framework Web Part.
         <br/>
         Message is : {{message}}
         <br/>
         Site URL is : {{siteUrl}}
       `,
   providers: []
})

export class AppComponent {

   @Input()
   public message: string;

   @Input()
   public siteUrl: string;
}

Update SharePoint Web Part

Now we need to updated the web part created with project to include our angular component. In Visual Studio Code, expand folders “src” -> “webparts” -> “myEvents” (this can be different based on the name provided while creating the project) and open “MyEventsWebPart.ts” file.
Add below import statements-
//Include Polyfills for unsupported browsers
import "@webcomponents/custom-elements/src/native-shim";
import "core-js/es7/reflect";

import { AppModule } from "./app/app.module";
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";
Replace the render method with below code-
public render(): void {

     platformBrowserDynamic().bootstrapModule(AppModule, {ngZone: 'noop'}).then(() => {
         this.domElement.innerHTML =`<my-app message="${this.properties.description}" site-url="${this.context.pageContext.web.absoluteUrl}"></my-app>`
     })
}
Now we are good to test our application. In the command prompt (should be open already from the previous steps), execute the below command-
//install developer certificate
gulp trust-dev-cert

//This will execute a series of gulp tasks and launches browser to preview web part
gulp serve
Click on add button and select “MyEvents” web part.
localworkbench
It should show a default message and URL of the site.
webpart
Now edit the web part and change description field to see the changes.
description
That means our integration is successful and its working.

Browser Support for Angular Elements

Browser Custom Element Support
Chrome Supported natively.
Opera Supported natively.
Safari Supported natively.
Firefox Set the dom.webcomponents.enabled and dom.webcomponents.customelements.enabledpreferences to true. Planned to be enabled by default in version 60/61.
Edge Working on an implementation.

References

GitHub Repository

Code can be downloaded from the GitHub Repository here.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s