How To Read SharePoint TermStore Managed Metadata In SharePoint Framework (SPFx) With Angular

Introduction

This article demonstrates how to read SharePoint TermStore data in SPFx applications. Since we don’t have direct REST API support for this service, we will be using the old JSOM method to read TermStore in the SharePoint Framework web part.

Implementation

Though SPFx directly provides the user context without writing a single piece of code, to get access to TermStore, we still need old SP.PageContext info help. Let’s get to know about loading _spPageContextInfo and Termsets altogether in all new SPFx with the help of SPComponentLoader.

The below implementation will fit all types of JS frameworks supported by SharePoint Framework web parts.

Please follow the steps below and the code snippets.

Step 1. Go to your tsconfig.json file in the SPFx web part project and make sure to add the "Microsoft-ajax" and "SharePoint" types like below.

"types": [
  "webpack-env",
  "microsoft-ajax",
  "sharepoint"
],

Code Snippet: 1

Step 2. The next step is to add the required node module packages to your project through the package.json file, open the file, and add the dependencies for Microsoft-ajax and SharePoint, as shown below.

"@types/microsoft-ajax": "0.0.33",
"@types/mocha": ">=2.2.33 <2.6.0",
"@types/sharepoint": "^2013.1.6",

Code Snippet: 2

Now, go to your npm command prompt, make sure that the terminal is pointing to your project directory, and restore the newly added Angular 4 package dependencies by using the command -

npm install

Example. E:\your project directory >npm install

Now, we have set all the dependencies to read the TermStore using SharePoint Framework, and the final step is right below.

Last step

Go to the default webpart.ts file, which is located at the below location.

\\{solutiondirectory} > src > webparts > {webpartName}\{solutionName}WebPart.ts file generated by SPFx generator where you will append your HTML code to the DOM element.

Example. E:\first-spfx-webpart\src\webparts\helloworld\helloworldWebPart.ts

Now, we have to add the reference scripts to get the SP.PageContext. The scripts have to be referred to in proper order because one script depends on another one.

To load the scripts, we will be using SPComponentLoader.load script in Oninit() method of SPFx web part, and load the JS references listed here,

  • init.js,
  • MicrosoftAjas.js
  • SP.Runtime.js,
  • SP.js,
  • SP.Taxonomy.js

Please refer to the code snippet below.

protected onInit(): Promise<void> {  
    let siteColUrl = this.context.pageContext.site.absoluteUrl;  
    SPComponentLoader.loadScript(siteColUrl + '/_layouts/15/init.js', {  
        globalExportsName: '$_global_init'  
    })  
    .then((): Promise<{}> => {  
        return SPComponentLoader.loadScript(siteColUrl + '/_layouts/15/MicrosoftAjax.js', {  
            globalExportsName: 'Sys'  
        });  
    })  
    .then((): Promise<{}> => {  
        return SPComponentLoader.loadScript(siteColUrl + '/_layouts/15/SP.Runtime.js', {  
            globalExportsName: 'SP'  
        });  
    })  
    .then((): Promise<{}> => {  
        return SPComponentLoader.loadScript(siteColUrl + '/_layouts/15/SP.js', {  
            globalExportsName: 'SP'  
        });  
    })  
    .then((): Promise<{}> => {  
        return SPComponentLoader.loadScript(siteColUrl + '/_layouts/15/SP.taxonomy.js', {  
            globalExportsName: 'SP'  
        });  
    })  
    .then((): void => {  
        let spContext: SP.ClientContext = new SP.ClientContext(siteColUrl);  
        let taxSession = SP.Taxonomy.TaxonomySession.getTaxonomySession(spContext);  
        let termStore = taxSession.getDefaultSiteCollectionTermStore();  
        let termGroups = termStore.get_groups();  
        let termGroup = termGroups.getByName("People");  
        let termSets = termGroup.get_termSets();  
        this.loadDepartment(termSets, spContext);  
    });  

    return super.onInit();  
}

Code Snippet: 3

Now that we have the _spPageContext and TermSets in your scope, it is time to load specific term sets. Please see the below code snippet to load the ”Department” TermSets using spPageContext load and execute methods.

private loadDepartment(termSets: SP.Taxonomy.TermSetCollection, spContext: SP.ClientContext) {
    let termSet = termSets.getByName("Department");
    let terms = termSet.getAllTerms();
    spContext.load(terms);
    spContext.executeQueryAsync(function () {
        var termsEnum = terms.getEnumerator();
        let termDepartment: any[] = [];
        while (termsEnum.moveNext()) {
            var spTerm = termsEnum.get_current();
            termDepartment.push({
                label: spTerm.get_name(),
                value: spTerm.get_name(),
                id: spTerm.get_id()
            });
        }
        window['termDepartment'] = termDepartment;
    });
}

Code Snippet: 4

The last line of the above snippet highlighted in yellow color can be used to take your TermSet to angular four instances from the SPFx instance, and you can read this in your angular code with the below code snippet,

let termDepartmentList: any[] = window['termDepartment'];

Code Snippet: 5

Summary

In this article, I discussed how to load the SharePoint TermStore (Managed Metadata) by using JSOM Page context in SharePoint Framework (SPFx) integrated with Angular 4. In my next article, I will explain how to add/edit the TermStore values from SPFx web parts.

If you have any questions/issues about this article, please let me know in the comments.