DEV Community

Cover image for Integrating Angular with Contentstack
Sudhakar George
Sudhakar George

Posted on

Integrating Angular with Contentstack

Integrating Angular with Contentstack allows you to build powerful and dynamic web applications powered by a headless CMS.

What is ContentStack?

Contentstack is a headless content management system (CMS) that helps businesses manage content across multiple digital channels. It's designed to help companies create unique digital experiences, accelerate growth, and lower the cost of ownership.

Features

  • Headless
    Contentstack is not tied to a specific presentation layer, so it can serve content to any channel, such as websites, mobile apps, or marketing kiosks.

  • API-based
    Contentstack allows developers and content managers to work independently and simultaneously to create and manage content

  • Integrations
    Contentstack can connect with other tools and platforms, such as Marketo, Salesforce, and Google Analytics

How to integrate Contentstack with Angular:

Step 1: Create an Angular Project

Steps to create Angular Project from Scratch:

1) Install Angular CLI:

Angular CLI (Command Line Interface) is a powerful tool for creating and managing Angular projects. You can install it globally using npm by running the following command in your terminal or command prompt:

npm install -g @angular/cli

2) Create a New Angular Project:

Once Angular CLI is installed, you can use it to create a new Angular project. Navigate to the directory where you want to create your project and run the following command:

ng new angular-contentstack-example --no-standalone
Enter fullscreen mode Exit fullscreen mode

3) Serve Your Angular Application:

After the project is created, navigate into the project directory then use an Angular CLI to serve your application locally by running:

ng serve
Enter fullscreen mode Exit fullscreen mode

Step 2: Add and Configure Contentstack Angular Module

1) You need to start by installing the JavaScript SDK. Navigate to the root folder and run the following command:

npm install --save contentstack

Your package.json will be updated with the contentstack dependency as shown below:

Image description

2) Create ContentStack Module and Service

Create a src/modules/contentstack folder to add the ContentStack Modules and Service. It have following 3 files.

  1. config.ts
  2. contentstack.module.ts
  3. contentstack.service.ts

Image description

1) config.ts

It is a configuration file.

import { Injectable } from '@angular/core';

@Injectable()
export class Config {
    api_key: string;
    access_token: string;
    environment?: string;
  }
Enter fullscreen mode Exit fullscreen mode

2) contentstack.module.ts

import { ModuleWithProviders, NgModule, InjectionToken } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ContentstackService} from './contentstack.service';
import { Config } from './config';
export const CsbaseAppConfigToken = new InjectionToken<string>('CsbaseAppConfigToken');

export function _csbaseAppFactory(config) {
  try {
      return  new ContentstackService(config);
  } catch (e) {
    return new ContentstackService(null);
  }
}

const ContentstackAppProvider = {
  provide: ContentstackService,
  useFactory:  _csbaseAppFactory,
  deps: [ CsbaseAppConfigToken ]
};



@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [],
  providers: [ContentstackAppProvider]
})
export class ContentstackModule {

  static initializeApp(config: Config): ModuleWithProviders {
    return {
      ngModule: ContentstackModule,
      providers: [
        {provide: CsbaseAppConfigToken, useValue: config }
      ]
    };
  }

}
Enter fullscreen mode Exit fullscreen mode

3) contentstack.service.ts

import { Injectable } from '@angular/core';
import * as contentstack from 'contentstack/web';
import { Config } from './config';


@Injectable()
export class ContentstackService {
  Stack: any = {};
  stackConfig: any = {};
  constructor(private config: Config) {
    this.stackConfig = config;
    this.Stack = contentstack.Stack(config);
  }

  public stack() {
    return contentstack.Stack(this.stackConfig);
  }
}
Enter fullscreen mode Exit fullscreen mode

3) Configure ContentStack Module in Main App

Next, you need to configure the module. Add the contentstack module along with the config into your main App module:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ContentstackModule} from '../modules/contentstack/contentstack.module';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

const Config = {
  'api_key': 'YOUR_API_KEY',
  'delivery_token': 'YOUR_DELIVERY_TOKEN',
  'environment': 'YOUR_ENVIRONMENT'

 };

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ContentstackModule.initializeApp(Config)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Enter fullscreen mode Exit fullscreen mode

This adds the Contentstack Angular module in your App module along with the config required for retrieving data from Contentstack.

Important:

Replace YOUR_API_KEY, YOUR_DELIVERY_TOKEN, and YOUR_ENVIRONMENT with your actual Contentstack credentials.


4) Use the Service in your Components

Inject the Contentstack Service into your components to fetch and display content:

import { Component } from '@angular/core';
import { ContentstackService } from '../modules/contentstack/contentstack.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'angular-contentstack-example';
  constructor(private cs: ContentstackService) {}
  entryText:any = {};

  getEntry() {
   const Query = 
    this.cs.stack().ContentType('YOUR_CONTENT_TYPE').Query();
    Query.where('uid','YOUR_ENTRY_UID');
    Query
    .includeReference()
    .toJSON()
    .find()
    .then(
       entry => {
         this.entryText = entry[0][0];
       },
       err => {
         console.log(err, 'err');
       }
    ); 
}

 ngOnInit() {
  this.getEntry()
  }

}

Enter fullscreen mode Exit fullscreen mode

Important:

Replace YOUR_CONTENT_TYPE, YOUR_ENTRY_UID with your actual Contentstack credentials.

Content Type
Content type lets you define the structure or blueprint of a page or a section of your digital property. It is a form-like page that gives Content Managers an interface to input and upload content.

Entry
An entry is the actual piece of content created using one of the defined content types.

In your HTML you can iterate a data and map it according to your needs.

For Example

    @for (item of entryText.sections; track item; let index = $index) {
      <tr>
         <td>{{ index }} </td>
         <td>{{ entryText[index].form_name}} </td>
         <td>{{ entryText[index].script_text}}</td>
         <td>{{ entryText[index].label}}</td>
       </tr> 
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)