Angular Quick start guide
Estimated duration: 10 minutes
This guide shows you how to connect Prepr to an Angular project to get data from Prepr CMS. You'll learn how to make a simple blog with Angular and Prepr CMS. By the end of this guide, you'll have a working app that looks like the image below.
If you want to skip ahead, clone the repository on GitHub (opens in a new tab) to run the demo locally.
Prerequisites
You need to have the following setup before you connect your Angular project to Prepr.
- A free Prepr account (opens in a new tab)
- An environment with the demo content in Prepr
- The latest version of Node.js (opens in a new tab)
Step 1: Create a new Angular project
The instructions below will guide you on how to create an empty Angular project for your blog app. If you have an existing Angular project, then you can skip this step.
- Open a terminal, go to your development projects folder and execute the command below to install the latest Angular CLI:
npm i -g @angular/cli@latest
- Now that the Angular CLI is installed you can create an Angular project called
prepr-angular
. ChooseY
for each of the options.
ng new prepr-angular
- When the project is successfully created, execute the commands below to go to the
prepr-angular
folder, the root directory of the project, and start the project.
cd prepr-angular
ng serve --open
- A browser window opens automatically for you to view your app on your localhost, for example,
http://localhost:4200/
.
Step 2: Connect to Prepr
Set up a connection to Prepr to retrieve CMS data with GraphQL. The instructions below show you how to connect to Prepr directly from your project so that you can execute GraphQL queries to request data from the Prepr API.
- Stop the localhost website server (
CTRL-C
) if it's running and open your Angular project with your preferred code editor. - To store the Prepr endpoint value, create a new folder
environments
in theapp
directory and add the following code to a new fileenvironments.ts
in this folder.
export const environment = {
PREPR_ENDPOINT: '<YOUR-PREPR-GRAPHQL-URL>'
};
- Replace the placeholder value
<YOUR-PREPR-GRAPHQL-URL>
with the API URL of an access token from Prepr. Get an access token by logging into your Prepr account:
a. Go to Settings → Access tokens to view all the access tokens.
b. Click to open the GraphQL Production access token, and copy the API URL to only retrieve published content items on your site for now. c. Paste the copied API URL in your.env
file.
Use the GraphQL Production access token to request published content items for your live app and use the GraphQL Preview token to make a preview of unpublished content items for your content editors.
- To connect to Prepr GraphQL API, create a new
services
folder in theapp
directory and add the following code to a new file calledprepr.service.ts
:
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
@Injectable({
providedIn: 'root',
})
export class PreprService {
async fetchData(query: string, variables?: any): Promise<any> {
const response = await fetch(environment.PREPR_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ query, variables }),
});
return response.json();
}
}
- Execute the following command to restart the server.
npm start
If your app runs without errors, then the setup above was done correctly. The next step is to fetch content from Prepr using the endpoint that you set up.
Step 3: Fetch multiple articles
Now that your app is connected to Prepr, fetch the blog articles from Prepr.
Add a GraphQL query
-
Create a
queries
folder in theapp
folder and create a file namedget-articles.ts
. -
Add the following query to this file to retrieve all articles:
export const GetArticles = `
query {
Articles {
items {
_id
_slug
title
}
}
}
`
You can create and test GraphQL queries using the Apollo explorer (opens in a new tab) from Prepr. Open the API Explorer from the Article content item page in Prepr or the access token page.
If you’re using preloaded demo data in your Prepr CMS environment, as mentioned above in the Prerequisites section, you should have a few published articles as shown in the below image. The query will retrieve the ID, Slug, and Title of each article.
In the next step, we'll fetch and process the query response.
Fetch articles
Now that the query has been added, fetch the articles from Prepr and display them in the app. You can do this by creating an article overview page in the app, by following the instructions below.
- First, generate the article overview component to contain the code to fetch and render the list of articles with this command:
ng generate component article-overview
You'll see a new folder article-overview
in the app
folder with the generated files.
- To run the query and fetch the list of articles, replace the generated code with the code below in the
article-overview.component.ts
file.
import { Component, effect, inject } from '@angular/core';
import { PreprService } from '../services/prepr.service';
import { GetArticles } from '../queries/get-articles';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
@Component({
selector: 'app-article-overview',
imports: [CommonModule, RouterModule],
templateUrl: './article-overview.component.html',
styleUrls: ['./article-overview.component.css']
})
export class ArticleOverviewComponent {
articles: any[] = [];
private preprService = inject(PreprService);
constructor() {
effect(async () => {
const response = await this.preprService.fetchData(GetArticles);
this.articles = response.data.Articles.items;
});
}
}
- Clear out the existing HTML by replacing the code in the `app.component.html' with the simple code below:
<router-outlet />
- To display the list of articles, add the following code to the
article-overview.component.html
.
<h1>My blog site</h1>
<ul>
@for (article of articles; track article._slug) {
<li>
<a [routerLink]="article._slug">{{ article.title }}</a>
</li>
}
</ul>
- To include routing to the article overview component, add the following code to the
app.routes.ts
file:
import { Routes } from '@angular/router';
import {ArticleOverviewComponent} from './article-overview/article-overview.component';
export const routes: Routes = [
{
path: '',
component: ArticleOverviewComponent,
}
];
Now when you view the website on your localhost, you'll see something like the image below.
Step 4: Fetch individual articles
Now that you have the list of articles, you can create the article detail page for each article. When a visitor clicks an article link, your app should open a detailed article page automatically. The instructions below show you how to create a route from the main page to the detailed page and how to fetch the article details based on the slug of the article that was clicked.
Add a GraphQL query
Add another query to fetch a specific article by its slug and make this page visible when clicking an article.
- Create a file called
get-article-by-slug.ts
in thequeries
folder and add the following query to this file to query a specific article by its slug:
export const GetArticleBySlug = `
query ($slug: String) {
Article (slug: $slug) {
_id
title
content {
__typename
... on Text {
body
text
}
... on Assets {
items {
url
}
}
}
}
}`
Fetch article details
Now that the query has been added, fetch the individual article details by its slug and display them in the app. You can do this by creating an article detail page in the app, by following the instructions below.
- First, generate the article detail component to contain the code to fetch and render the article details with this command:
ng generate component article-detail
You'll see a new folder article-detail
with the generated files in the app
folder.
- To run the query and fetch the details of a specific article, replace the generated code with the code below in the
article-detail.component.ts
file.
import { Component } from '@angular/core';
import {Subscription} from "rxjs";
import {Apollo} from "apollo-angular";
import {GetArticles} from "../../queries/get-articles";
import {GetArticleBySlug} from "../../queries/get-article-by-slug";
import {ActivatedRoute, NavigationEnd, Router} from "@angular/router";
@Component({
selector: 'app-article-detail',
templateUrl: './article-detail.component.html',
styleUrls: ['./article-detail.component.css']
})
export class ArticleDetailComponent {
loading: boolean;
article: any;
slug: string;
private querySubscription: Subscription;
constructor(private apollo: Apollo, private router: Router, private activatedRoute:ActivatedRoute) {
this.slug = activatedRoute.snapshot.url[0].path;
}
ngOnInit() {
console.log(this.slug)
this.querySubscription = this.apollo
.watchQuery<any>({
query: GetArticleBySlug,
variables: {
slug: this.slug
}
})
.valueChanges.subscribe(({ data, loading }) => {
this.loading = loading;
this.article = data.Article;
console.log(data.Article)
});
}
ngOnDestroy() {
this.querySubscription.unsubscribe();
}
}
The Article content is stored in a Dynamic content field. Check out the GraphQL docs for more details on how to fetch the data within this field.
- To display the article details, add the below code to the
article-detail.component.html
.
<div>
<h1>
{{ article.title }}
</h1>
<div *ngFor='let contentType of article.content;'>
<div *ngIf='contentType.__typename === "Assets" && contentType.items.length'>
<img
src='{{contentType.items[0]?.url}}'
width="300"
height="250"
/>
</div>
<div *ngIf='contentType.__typename === "Text"' innerHTML="{{contentType.body}}">
</div>
</div>
</div>
- To include routing to the article detail component, add the following code to the
app.routes.ts
file:
import { Routes } from '@angular/router';
import {ArticleOverviewComponent} from './article-overview/article-overview.component';
import {ArticleDetailComponent} from './article-detail/article-detail.component';
export const routes: Routes = [
{
path: '',
component: ArticleOverviewComponent,
},
{
path: ':slug',
component: ArticleDetailComponent,
},
];
Now, when you view your site, you can click on an article which will direct you to that specific article like in the image below.
All done
Congratulations! You have successfully connected an Angular project to Prepr for a simple Blog app.
Next steps
To learn more on how to expand your project, check out the following resources:
Was this article helpful?
We’d love to learn from your feedback