All Blogs

Running a 3D Angular application in Astro via AnalogJS

What is Astro?

Astro is a high-performance framework designed to seamlessly merge the benefits of static and dynamic web development. It empowers developers to build modern websites using their preferred JavaScript frameworks while delivering lightning-fast loading times. With its unique “universal rendering” approach, Astro pre-renders pages into static HTML for optimal performance and security, while still enabling client-side interactivity. By leveraging partial hydration and other optimization techniques, Astro ensures efficient component loading and a superior user experience.

Recently, Astro has released version 3 with tons of improvements. I figure this is good timing to write some content for Astro and Angular since we’re going to use Astro to render our Angular components.

What is AnalogJS?

Analog is a fullstack meta-framework for building applications and websites with Angular. Additionally, Analog provides an Astro Integration that we can utilize to render Angular components in Astro.

What is Angular Three?

angular-three is a custom Angular Renderer to render THREE.js entities directly to the HTMLCanvasElement instead of the DOM.

Create an Astro application

Getting started with Astro is super easy because they provide a CLI tool to create a new Astro application

Open up the terminal and enter the following command

Terminal window
1
npm create astro

Follow the prompts by create-astro. If you’re wondering, here’s mine

npm create astro prompts npm create astro prompts

Add AnalogJS integration

To add AnalogJS integration to Astro, run the following command

Terminal window
1
npx astro add @analogjs/astro-angular

Say Yes to both questions and our Astro application is ready to render some Angular components

Add tsconfig.app.json

Although we have added the Astro integration, we need to create a tsconfig.app.json at the project’s root.

Start by creating tsconfig.app.json

Terminal window
1
touch tsconfig.app.json

Then fill it out with the following content

1
{
2
"extends": "./tsconfig.json",
3
"compileOnSave": false,
4
"compilerOptions": {
5
"baseUrl": "./",
6
"outDir": "./dist/out-tsc",
7
"forceConsistentCasingInFileNames": true,
8
"strict": true,
9
"noImplicitOverride": true,
10
"noPropertyAccessFromIndexSignature": true,
11
"noImplicitReturns": true,
12
"noFallthroughCasesInSwitch": true,
13
"sourceMap": true,
14
"declaration": false,
15
"downlevelIteration": true,
16
"experimentalDecorators": true,
17
"moduleResolution": "node",
18
"importHelpers": true,
19
"noEmit": false,
20
"target": "es2022",
21
"module": "es2022",
22
"lib": ["es2022", "dom"],
23
"skipLibCheck": true
24
},
25
"angularCompilerOptions": {
26
"enableI18nLegacyMessageIdFormat": false,
27
"strictInjectionParameters": true,
28
"strictInputAccessModifiers": true,
29
"strictTemplates": true,
30
"allowJs": false
31
},
32
"files": [],
33
"include": ["src/**/*.ts", "src/**/*.tsx"]
34
}

Add our first Angular component

Create a new file, Experience.ts, in src/components

You can use any file name for the component.

Terminal window
1
touch src/components/Experience.ts

Then fill it out with the following boilerplate

1
import { Component } from "@angular/core";
2
3
@Component({
4
standalone: true,
5
template: `
6
Hello Angular
7
`,
8
})
9
export class Experience {}

AnalogJS’s Astro integration requires components to be standalone: true

To use this Experience component, open up src/pages/index.astro

Import Experience component

1
import Layout from '../layouts/Layout.astro';
2
import Card from '../components/Card.astro';
3
import { Experience } from '../components/Experience';

Then render the component using the name of the component <Experience />

1
<h1>Welcome to <span class="text-gradient">Astro</span></h1>
2
<p class="instructions">
3
To get started, open the directory <code>src/pages</code> in your project.<br
4
/>
5
<strong>Code Challenge:</strong> Tweak the "Welcome to Astro" message above.
6
</p>
7
8
<Experience />
9
10
<ul role="list" class="link-card-grid">
11
<!-- ... -->
12
</ul>

Start our Astro application’s development server with the following command

Terminal window
1
npm run dev

Then go to http://localhost:4321 and we’ll see our Experience component is rendered 🎊

Astro home page with Angular component rendered Astro home page with Angular component rendered

At this point, we can technically start writing blog posts with Astro and Angular

Add Angular Three

Open up the terminal so we can install a few things

Terminal window
1
npm install angular-three@beta three three-stdlib
2
npm install -D @types/three

We might need to run npm install with --force flag due to peer dependencies resolution

Let’s go back to Experience.ts and add the following code

1
import { CUSTOM_ELEMENTS_SCHEMA, Component } from "@angular/core";
2
import { NgtCanvas } from "angular-three";
3
4
@Component({
5
standalone: true,
6
template: ``,
7
schemas: [CUSTOM_ELEMENTS_SCHEMA],
8
})
9
class Scene {}
10
11
@Component({
12
standalone: true,
13
template: `
14
<ngt-canvas [sceneGraph]="scene" />
15
`,
16
imports: [NgtCanvas],
17
})
18
export class Experience {
19
scene = Scene;
20
}

You can also break up Scene into a separate file

Since Three.js is a Canvas-base library (i.e: WebGL), we want to enable client-side JavaScript for our Experience component. Astro allows us to do so by using client:load directive on our component. So, let’s go back to src/pages/index.astro and make the following change

1
<Experience />
2
<Experience client:load />

Additionally, we also need to update astro.config.mjs with the following change:

1
export default defineConfig({
2
integrations: [analogjsangular()],
3
vite: {
4
ssr: {
5
noExternal: ["angular-three", "three", "ngx-resize"],
6
},
7
},
8
});

If you do not care about SSR, you can skip the config change and use client:only instead of client:load. This makes Experience component to only ever load on the client.

Make sure there is no error from our development server as well as in the browser’s console. Now, we are ready to render some 3D objects

Add our cube

Angular Three is a Custom Renderer. Hence, we need to teach it how to render tags that we put on the template, like how Angular knows how to render <div> into an HTMLDivElement on the DOM.

To do so, we’ll use extend() API from angular-three to expand the internal catalogue of Angular Three

1
import { NgtCanvas } from "angular-three";
2
import { NgtCanvas, extend } from "angular-three";
3
import { Mesh, MeshBasicMaterial, BoxGeometry } from "three";
4
5
extend({ Mesh, MeshBasicMaterial, BoxGeometry });

Here, we are teaching Angular Three how to render a THREE.Mesh, a THREE.MeshBasicMaterial, and a THREE.BoxGeometry

1
@Component({
2
standalone: true,
3
template: `
4
<ngt-mesh>
5
<ngt-box-geometry />
6
<ngt-mesh-basic-material color="hotpink" />
7
</ngt-mesh>
8
`,
9
schemas: [CUSTOM_ELEMENTS_SCHEMA],
10
})
11
class Scene {}

Notice how we use ngt-* to render our 3D objects. extend() turns what we pass in into a catalogue of HTML Custom Element tags prefixed with ngt- followed by the name of the entity in kebab-case. This is also the reason why we need CUSTOM_ELEMENTS_SCHEMA.

Now, our Astro application renders a pink “box”

Astro home page a pink box Astro home page a pink box

Increase the Canvas area

Our canvas is a little too small. This is because of two reasons:

NgtCanvas component is designed to take on the parent’s dimensions. Hence, we can control our canvas’ sizes by wrapping <Experience /> with a container with a specified height

1
<div style="height: 600px">
2
<Experience client:load />
3
</div>

The canvas will take up 600px and our pink box will be more visible.

Astro home page a pink box on a large canvas Astro home page a pink box on a large canvas

Animate the box

To animate our box, we can use (beforeRender) output on <ngt-mesh>

1
import { NgtCanvas, extend } from "angular-three";
2
import { NgtCanvas, extend, type NgtBeforeRenderEvent } from "angular-three";
3
4
@Component({
5
standalone: true,
6
template: `
7
<ngt-mesh>
8
<ngt-mesh (beforeRender)="onBeforeRender($event)">
9
<ngt-box-geometry />
10
<ngt-mesh-basic-material color="hotpink" />
11
</ngt-mesh>
12
`,
13
schemas: [CUSTOM_ELEMENTS_SCHEMA],
14
})
15
class Scene {
16
onBeforeRender({ object, state }: NgtBeforeRenderEvent<THREE.Mesh>) {
17
object.rotation.x += state.delta;
18
object.rotation.y += state.delta;
19
}
20
}

(beforeRender) allows our objects to participate in the animation loop that Angular Three creates to render the Scene Graph. This function runs outside of Angular Zone (i.e: outside of Angular Change Detection mechanism) to maintain high FPS. It is good practice to NOT update states in this function.

A rotating pink box A rotating pink box

Let there be lights

At the moment, our “box” looks bland. In fact, we can’t even tell if it’s a box. The reason is we’re using MeshBasicMaterial for our box and MeshBasicMaterial does not reflect lights. Let’s switch to MeshStandardMaterial, a material that can reflect lights.

1
import { BoxGeometry, Mesh, MeshBasicMaterial } from "three";
2
import { BoxGeometry, Mesh, MeshStandardMaterial } from "three";
3
4
extend({ Mesh, MeshBasicMaterial, BoxGeometry });
5
extend({ Mesh, MeshStandardMaterial, BoxGeometry });

Then we can update our template

1
<ngt-mesh (beforeRender)="onBeforeRender($event)">
2
<ngt-box-geometry />
3
<ngt-mesh-basic-material color="hotpink" />
4
<ngt-mesh-standard-material color="hotpink" />
5
</ngt-mesh>

But wait, our box is now pitch black.

A 'black' box A 'black' box

We haven’t added any lights yet. Imagine a dark room, there is no light that our box can reflect on. Let’s add some lights

1
import {
2
AmbientLight,
3
BoxGeometry,
4
DirectionalLight,
5
Mesh,
6
MeshStandardMaterial,
7
} from "three";
8
9
extend({
10
Mesh,
11
MeshStandardMaterial,
12
BoxGeometry,
13
AmbientLight,
14
DirectionalLight,
15
});

Next, let’s update our template to render those lights

1
@Component({
2
standalone: true,
3
template: `
4
<ngt-ambient-light [intensity]="Math.PI" />
5
<ngt-directional-light [intensity]="Math.PI" />
6
7
<ngt-mesh (beforeRender)="onBeforeRender($event)">
8
<ngt-box-geometry />
9
<ngt-mesh-standard-material color="hotpink" />
10
</ngt-mesh>
11
`,
12
schemas: [CUSTOM_ELEMENTS_SCHEMA],
13
})
14
class Scene {
15
Math = Math;
16
17
onBeforeRender({ object, state }: NgtBeforeRenderEvent<THREE.Mesh>) {
18
object.rotation.x += state.delta;
19
object.rotation.y += state.delta;
20
}
21
}

Voila! Now our box looks so much better, with dimensionality, like a real box.

A 'real' rotating pink box A 'real' rotating pink box

Take control of the camera

Who hasn’t tried to “grab” the scene and rotate it around? Well, we can’t with what we currently have because our camera is static. However, we will be able to control our camera with the help of OrbitControls

Let’s teach Angular Three how to render OrbitControls

1
import { OrbitControls } from "three-stdlib";
2
3
extend({
4
Mesh,
5
MeshStandardMaterial,
6
BoxGeometry,
7
AmbientLight,
8
DirectionalLight,
9
OrbitControls,
10
});

Next, let’s adjust our Scene component to render OrbitControls

1
import {
2
NgtCanvas,
3
extend,
4
type NgtBeforeRenderEvent,
5
injectNgtStore,
6
NgtArgs,
7
} from "angular-three";
8
9
@Component({
10
standalone: true,
11
template: `
12
<ngt-ambient-light [intensity]="Math.PI" />
13
<ngt-directional-light [intensity]="Math.PI" />
14
15
<ngt-mesh (beforeRender)="onBeforeRender($event)">
16
<ngt-box-geometry />
17
<ngt-mesh-standard-material color="hotpink" />
18
</ngt-mesh>
19
20
<ngt-orbit-controls *args="[camera(), domElement()]" />
21
`,
22
imports: [NgtArgs],
23
schemas: [CUSTOM_ELEMENTS_SCHEMA],
24
})
25
class Scene {
26
Math = Math;
27
28
private store = injectNgtStore();
29
camera = this.store.select("camera");
30
domElement = this.store.select("gl", "domElement");
31
32
onBeforeRender({ object, state }: NgtBeforeRenderEvent<THREE.Mesh>) {
33
object.rotation.x += state.delta;
34
object.rotation.y += state.delta;
35
}
36
}

Back to our running application and BOOM 💥, we can grab the scene, rotate it around, and zoom in/out

Controlling the camera with OrbitControls Controlling the camera with OrbitControls

Conclusion

Astro is truly a magnificient technology. It is light-weight, wicked fast, and easy to integrate with other frameworks. On the other hand, I cannot praise AnalogJS enough for what it enables for Angular developers. In this blog post, we learn how to use AnalogJS to bring Angular components to Astro land with an example of rendering a 3D box using Angular Three.

Give Astro, AnalogJS, and Angular each a star if you haven’t. I hope you have fun with all the technologies that we talk about in this blog post. See you in the next one.

Published on Thu Aug 31 2023


Angular Analog Astro