Monday, 11 November 2024

Setting Up an Angular Application (18) in SharePoint Framework (SPFx)

Introduction:

This guide will walk you through the process of integrating Angular with SharePoint Framework (SPFx), ideal for developers aiming to build dynamic applications within SharePoint. You'll learn how to set up the environment, configure Angular with SPFx, and deploy your application. This setup enables you to leverage Angular's capabilities while working within the SharePoint ecosystem.

Prerequisites:

Ensure that the following software and tools are installed:

  1. SharePoint SPFx Environment:  Set up the SharePoint SPFx environment. Follow the official guide here: Microsoft SPFx Setup.
  2. Node.js : Install Node.js version 18.
  3. Angular CLIInstall Angular CLI globally using: npm install -g @angular/cli

Note: Running `npm install -g @angular/cli` will install the latest version. To specify version 18, use `npm install -g @angular/cli@18`.

  • Code Editor:
    Install any code editor of your choice. Visual Studio Code is recommended for ease of use with SPFx.
Install any code editor of your choice. Visual Studio Code is recommended for ease of use with SPFx.

Steps to Create an SPFx Application with Angular

Step 1: Create an Angular Workspace

1. Open PowerShell (or an alternative command line) and navigate to your desired directory (e.g.): cd "D:\AKS\SPFX\Demo_spfx_ang"

2. Create a new Angular application using the command: ng new ang-app

3. When prompted:

  • Choose a stylesheet format: Select `css` (or your preferred option).
  • - Enable Server-Side Rendering (SSR) and Static Site Generation (SSG/Prerendering)?: Select `N`.

*SSR renders a fully front-end application on the server instead of the browser, while SSG creates a set of static HTML files for the app. Selecting 'No' simplifies the setup for basic applications.*

4. The command will install the required packages and set up your Angular solution. Ignore any Git configuration errors.

5. Once installation is complete, open your project in Visual Studio Code: code .

Step 2: Add Angular Elements

1. Open the terminal in Visual Studio Code and navigate to your Angular project: cd ang-app

2. Install the Angular Elements package: npm install @angular/elements@latest

3. Test the Angular Application :ng serve

If the application loads successfully in the browser, your setup is correct.


*Note: Angular will generate additional files (e.g., `polyfill.js`, `main.js`, `styles.js`) during build, which are required for SPFx.*


Step 3: Create the SPFx Application

1. Navigate back to your root directory in PowerShell and create a new folder for the SPFx application: cd "D:\AKS\SPFX\Demo_spfx_ang\spfx_app"

2. Create a new SPFx web part using the Yeoman generator: yo @microsoft/sharepoint

3. When prompted by Yeoman, configure as follows:

  • Component Type: WebPart
  • Web Part Name: Choose a descriptive name for your web part.
  • Template: Select 'No framework.'

4. Once Yeoman creates the project structure and installs dependencies, lock the packages to prevent version conflicts: npm shrinkwrap

5. Open the root folder in Visual Studio Code: code .

Step 4: Configure Angular to Work with SPFx

Modify angular.json

  1. Create an appfiles folder in the SPFx web part project (spfxAppWebPart).

  2. In angular.json (in the Angular project), update the outputPath to:

    "outputPath": "../spfx-app/src/webparts/spfxAppWebpart/appfiles"

    This change will ensure required files (polyfill.js, main.js, styles.js) are compiled into the appfiles folder.

  3. Change outputHashing to "none":

    "outputHashing": "none"

    This prevents adding unique hashes to filenames, so you won’t need to update file references in SPFx every time you rebuild the Angular project.

  4. Increase the budgets for maximumWarning and maximumError if necessary (optional):

    "maximumWarning": "5mb",
    "maximumError": "20mb"

    This adjustment helps avoid errors if the project exceeds default file size limits.

    So Overall changes in the angular.json will be as follows:


     

Modify main.ts

Update main.ts to define Angular components as custom elements:

import { ApplicationRef } from '@angular/core';
import { createApplication } from '@angular/platform-browser'; import { createCustomElement } from '@angular/elements'; import { appConfig } from './app/app.config'; import { AppComponent } from './app/app.component'; (async () => { const app: ApplicationRef = await createApplication(appConfig); const appComponent = createCustomElement(AppComponent, { injector: app.injector }); customElements.define('app-root', appComponent); })();


Note: Replace AppComponent with your default component if it differs.

Step 5: Integrate Angular with SPFx Web Part

  1. Import Angular Files in SPFx

    In the Webpart.ts file, add the following lines to import Angular styles and scripts:

    require('./appfiles/browser/styles.css');
    require('./appfiles/browser/polyfills.js'); require('./appfiles/browser/main.js');

    Order matters: Ensure these files are imported in this exact sequence.


  2. Render the Angular Component

    In the render() method of Webpart.ts, add:

    this.domElement.innerHTML = `<app-root></app-root>`;



Step 6: Testing the SPFx Application

  1. Trust the Developer Certificate
    Change to the SPFx app directory and run: gulp trust-dev-cert

    This step adds SPFx’s certificate to the trusted authorities on your machine.

  2. Change the {tenantDomain} with your SharePoint online site url. 


  3. Serve the Applicationgulp serve

    This will compile the solution and launch the SharePoint Workbench. Add the new web part to the Workbench to verify functionality.


Conclusion

Following these steps, you’ll have successfully set up an Angular application within the SharePoint Framework. This setup provides the flexibility to use Angular features in SPFx and offers a straightforward path for developing complex SharePoint solutions.

Cheers and happy coding!😊