SharePoint Framework. Create Angular WebPart

SharePoint Framework allows to create powerful extensions and web part for SharePoint Online (Office 365) and SharePoint on-premise. By default yeoman generator for SharePoint Framework supports only React and Knockout frameworks.

If you already have Angular skills you can use this guide to start applying your knowledge.

Seven steps to create a simple Angular client web part using SharePoint Framework.

In my previous post, you can find out the sample client web part based on AngularJS (in Russian).

Step #1. yoman

First of all start yeoman generator:

yo @microsoft/sharepoint

And choose options like on the screen:

Step #2. package.json

Open package.json and add the following lines (highlighted in blue):

{
  "name": "spfx-demo-angular",
  "version": "0.0.1",
  "private": true,
  "engines": {
    "node": ">=0.10.0"
  },
  "scripts": {
    "build": "gulp bundle",
    "clean": "gulp clean",
    "test": "gulp test"
  },
  "dependencies": {
    "@angular/common": "~4.0.0",
    "@angular/compiler": "~4.0.0",
    "@angular/core": "~4.0.0",
    "@angular/platform-browser": "~4.0.0",
    "@angular/platform-browser-dynamic": "~4.0.0",**
    "@microsoft/sp-core-library": "1.5.0",
    "@microsoft/sp-lodash-subset": "1.5.0",
    "@microsoft/sp-office-ui-fabric-core": "1.5.0",
    "@microsoft/sp-webpart-base": "1.5.0",
    "@types/es6-promise": "0.0.33",
    "@types/webpack-env": "1.13.1",
    "lodash": "^4.17.10",
    "reflect-metadata": "0.1.10",
    "rxjs": "~5.0.1",
    "systemjs": "0.19.40",
    "typescript-string-operations": "~1.1.0",
    "typings": "^2.1.1",
    "zone.js": "~0.8.4"**
  },
  "devDependencies": {
    "@microsoft/sp-build-web": "1.5.0",
    "@microsoft/sp-module-interfaces": "1.5.0",
    "@microsoft/sp-webpart-workbench": "1.5.0",
    "gulp": "~3.9.1",
    "@types/chai": "3.4.34",
    "@types/mocha": "2.2.38",
    "ajv": "~5.2.2"
  }
}

Step #3. tsconfig.json

Modify file tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "forceConsistentCasingInFileNames": true,
    "module": "commonjs",
    "jsx": "react",
    "declaration": true,
    "sourceMap": true,
    "experimentalDecorators": true,
    "skipLibCheck": true,
    "typeRoots": [
      "./node_modules/@types",
      "./node_modules/@microsoft"
    ],
    "types": [
      "webpack-env"
    ],
    "lib": [
      "dom",
      "dom.iterable",
      "es2015",
      "scripthost"
    ],
  },
  "compileOnSave": true**
}

Step #4. npm install

Save modified files and run the following command to install necessary packages (which were added in step #2):

npm install

The client web part now is ready for Angular.

Sample Angular app contains modules, components, and HTML templates. All we need is just build the module into the SPFX web part.

There are thee files for the app in the solution:

Step #5. Angular Module

Module registers single component to render the data:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';**

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent**],
  providers: [],
  bootstrap: [AppComponent**]
})

export class AppModule { }

Step #6. Angular Component

Component has two parts: TypeScript code and HTML template. Code:

import { Component, Input, OnInit } from '@angular/core';
import { WebPartContext } from '@microsoft/sp-webpart-base';
// WebPart Properties
import { IHelloWorldWebPartProps } from '../HelloWorldWebPart';

@Component({
  selector: "spfx-app", // Selector
  template: require("./template.component.html") as string // Template
})
export class AppComponent implements OnInit {
  // Properties
  public ctx: WebPartContext;
  public properties: IHelloWorldWebPartProps;

  constructor() {
  }

  public ngOnInit() {
    // Get context from window variable
    this.ctx = window["MyAngularWebPartContext"];
    // Get webpart properties
    this.properties = window["MyAngularWebPartProperties"];
  }
}

Selector spfx-app is used for app binding to HTML node. ctx property used for getting the context of the web part and properties one for web part properties.

Step #7. Client WebPart

To integrate described angular app to the client web part, modify HelloWorldWebPart.ts file:

import "reflect-metadata";
require('zone.js');
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { Version } from '@microsoft/sp-core-library';
import { BaseClientSideWebPart, IPropertyPaneConfiguration, PropertyPaneTextField } from '@microsoft/sp-webpart-base';
import * as strings from 'HelloWorldWebPartStrings';
export interface IHelloWorldWebPartProps {
}

export default class HelloWorldWebPart extends BaseClientSideWebPart<IHelloWorldWebPartProps> {

  public render(): void {
    // Save context and properties to window variable
    window["MyAngularWebPartContext"] = this.context;
    window["MyAngularWebPartProperties"] = this.properties;

    // Angular app element
    // spfx-app is the selector for Angular component
    this.domElement.innerHTML = '<spfx-app>Loading...</spfx-app>';

    // bootstrapModule
    platformBrowserDynamic().bootstrapModule(AppModule);
  }

  protected get dataVersion(): Version {
    return Version.parse('1.0');
  }

  protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
    return {
      pages: [
        {
          header: {
            description: strings.PropertyPaneDescription
          },
          groups: [
            {
              groupName: strings.BasicGroupName,
              groupFields: [
                PropertyPaneTextField('description', {
                  label: strings.DescriptionFieldLabel
                })
              ]
            }
          ]
        }
      ]
    };
  }
}

Pay your attention to render method: current context and web part properties stored in window variables (angular component read this data).

At the end of this method, we bootstrap angular app.

Done!

That's it! Run the following command to start a workbench and see the result:

Code

The project is published here: https://github.com/vzhukov/spfx-demo-angular

Vitaly Zhukov

Vitaly Zhukov

SharePoint Architect, Developer, Technical Trainer, Microsoft MVP (Office Development). Above 15 years of total experience working with SharePoint, Dynamics CRM, Office 365, and Microsoft stack development.

You May Also Like

Provision Lists and Libraries with SPFx solution

Provision Lists and Libraries with SPFx solution

SharePoint. Drag-and-Drop File Uploading

SharePoint. Drag-and-Drop File Uploading

CSOM. Upload document

CSOM. Upload document

SharePoint List REST API. Part 2

SharePoint List REST API. Part 2

SharePoint List REST API. Part 1

SharePoint List REST API. Part 1

Project Server. CSOM + Custom Fields

Project Server. CSOM + Custom Fields

SharePoint 2010. Long time operation with updatable status

SharePoint 2010. Long time operation with updatable status

Linq to SharePoint. Cross site collection queries

Linq to SharePoint. Cross site collection queries

SharePoint. Getting Document Icon URL

SharePoint. Getting Document Icon URL

Linq to SharePoint. Repository pattern

Linq to SharePoint. Repository pattern

Linq to SharePoint vs Camlex.NET Performance Comparison

Linq to SharePoint vs Camlex.NET Performance Comparison

Linq to SharePoint. Part 5. Choice and MultiChoice fields

Linq to SharePoint. Part 5. Choice and MultiChoice fields

Linq to SharePoint. Part 4

Linq to SharePoint. Part 4

Linq to SharePoint. Part 3

Linq to SharePoint. Part 3

Linq to SharePoint. Part 2

Linq to SharePoint. Part 2

Linq to Sharepoint. Part 1

Linq to Sharepoint. Part 1