Skip to content

docs(example): Angular - Template Hierarchy & Data Fetch #325

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions examples/angular/template-hierarchy-data-fetching/.wp-env.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"phpVersion": "8.3",
"plugins": [
"https://github.com/wp-graphql/wp-graphql/releases/latest/download/wp-graphql.zip",
"https://downloads.wordpress.org/plugin/classic-editor.latest-stable.zip",
"https://downloads.wordpress.org/plugin/wpgraphql-ide.latest-stable.zip"
],
"themes": [
"https://downloads.wordpress.org/theme/twentytwentyone.latest-stable.zip"
],
"env": {
"development": {
"port": 8892
},
"tests": {
"port": 8893
}
},
"config": {
"WP_DEBUG": true,
"SCRIPT_DEBUG": false,
"GRAPHQL_DEBUG": true,
"WP_DEBUG_LOG": true,
"WP_DEBUG_DISPLAY": false,
"SAVEQUERIES": false
},
"mappings": {
"db": "./wp-env/db",
"wp-content/uploads": "./wp-env/uploads",
".htaccess": "./wp-env/setup/.htaccess"
},
"lifecycleScripts": {
"afterStart": "wp-env run cli -- wp theme activate twentytwentyone && wp-env run cli -- wp theme delete --all && wp-env run cli -- wp plugin delete hello-dolly && wp-env run cli -- wp rewrite structure '/%postname%/' && wp-env run cli -- wp rewrite flush"
}
}
20 changes: 20 additions & 0 deletions examples/angular/template-hierarchy-data-fetching/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Angular Template Hierarchy and Data fetching Example

In this example we show how to implement the WordPress Template Hierarchy in Angular for use with a Headless WordPress backend using WPGraphQL.

## Getting Started

> [!IMPORTANT]
> Docker Desktop needs to be installed to run WordPress locally.

1. Run `npm run example:setup` to install dependencies and configure the local WP server.
2. Run `npm run backend:start` starts the backend server for template fetching at http://localhost:3000/api/templates
3. Run `npm run example:start` to start the WordPress server and Angular development server.

> [!NOTE]
> When you kill the long running process this will not shutdown the local WP instance, only Angular. You must run `npm run example:stop` to kill the local WP server.

## Trouble Shooting
1. I get "Page Not Found. Sorry, the page you are looking for does not exist. Please check the URL." when opening the Angular app and trying to navigate through it.
- Run `npm run backend:start` and verify that http://localhost:3000/api/templates returns correct data
2. To reset the WP server and re-run setup you can run `npm run example:prune` and confirm "Yes" at any prompts.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Angular Backend Service for fetching WordPress templates

Used purely to fetch dynamically the available templates in `/example-app/src/app/components/wp-templates`

## Getting Started

1. Run `npm run dev` to start backend service for fetching templates at `http://localhost:3000/api/templates`. It fetches the templates located in `/example-app/src/app/components/wp-templates`.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "backend",
"version": "1.0.0",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^17.2.0",
"express": "^5.1.0"
},
"devDependencies": {
"@types/node": "^24.0.14",
"nodemon": "^3.1.10",
"tsx": "^4.20.3"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import express from 'express';
import { readdir } from 'node:fs/promises';
import { join, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import cors from 'cors';
import dotenv from 'dotenv';

dotenv.config();

const app = express();
const port = process.env.PORT || 3000;

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const TEMPLATES_PATH = process.env.TEMPLATE_PATH ||
resolve(__dirname, '../example-app/src/app/components/wp-templates');

app.use(cors({
origin: process.env.FRONTEND_URL
}));

app.get('/api/templates', async (req, res) => {
//console.log(`🔍 Reading templates from: ${TEMPLATES_PATH}`);

try {
try {
await readdir(TEMPLATES_PATH);
} catch (error) {
throw new Error(`Template directory does not exist: ${TEMPLATES_PATH}`);
}

const entries = await readdir(TEMPLATES_PATH, { withFileTypes: true });

const templates = [];

for (const entry of entries) {
if (entry.isDirectory() &&
!entry.name.startsWith("+") &&
!entry.name.startsWith("_") &&
!entry.name.startsWith(".")) {

const folderPath = join(TEMPLATES_PATH, entry.name);

try {
const folderContents = await readdir(folderPath);
const hasComponentFile = folderContents.some(file =>
file.endsWith('.component.ts')
);

if (hasComponentFile) {
templates.push({
id: entry.name,
path: `/wp-templates/${entry.name}`,
});
//console.log(`✅ Added template: ${entry.name}`);
}
} catch (error) {
//console.warn(`❌ Could not read template folder: ${entry.name}`, error.message);
}
}
}

res.json(templates);

} catch (error) {
//console.error('❌ Error reading template directories:', error);

// Return fallback templates
const fallbackTemplates = [
{ id: 'front-page', path: '/wp-templates/front-page' },
{ id: 'home', path: '/wp-templates/home' },
{ id: 'page', path: '/wp-templates/page' },
{ id: 'single', path: '/wp-templates/single' },
{ id: 'archive', path: '/wp-templates/archive' },
];

res.status(500).json(fallbackTemplates);
}
});

app.listen(port, () => {
// console.log(`🚀 Template discovery API running at http://localhost:${port}`);
// console.log(`📂 Templates path: ${TEMPLATES_PATH}`);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Editor configuration, see https://editorconfig.org
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true

[*.ts]
quote_type = single
ij_typescript_use_double_quotes = false

[*.md]
max_line_length = off
trim_trailing_whitespace = false
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files.

# Compiled output
/dist
/tmp
/out-tsc
/bazel-out

# Node
/node_modules
npm-debug.log
yarn-error.log

# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace

# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*

# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings

# System files
.DS_Store
Thumbs.db
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"my-app": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular/build:application",
"options": {
"browser": "src/main.ts",
"tsConfig": "tsconfig.app.json",
"assets": [
{
"glob": "**/*",
"input": "public"
}
],
"styles": [
"src/app/assets/scss/global.scss"
],
"server": "src/main.server.ts",
"outputMode": "server",
"ssr": {
"entry": "src/server.ts"
}
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1MB"
},
{
"type": "anyComponentStyle",
"maximumWarning": "4kB",
"maximumError": "8kB"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular/build:dev-server",
"configurations": {
"production": {
"buildTarget": "my-app:build:production"
},
"development": {
"buildTarget": "my-app:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular/build:extract-i18n"
},
"test": {
"builder": "@angular/build:karma",
"options": {
"tsConfig": "tsconfig.spec.json",
"assets": [
{
"glob": "**/*",
"input": "public"
}
],
"styles": [
"src/app/assets/scss/global.scss"
]
}
}
}
}
},
"cli": {
"analytics": "08503614-9520-4065-9a5e-b3cdbd31cb2a"
}
}
Loading