Skip to content

Routed Scene

Angular Three supports routed scenes. This is useful for when you want to have different scene graphs for different routes but keep the root NgtCanvas component the same.

To enable routed scenes, pass 'routed' to the sceneGraph input of the NgtCanvas component.

<ngt-canvas sceneGraph="routed" />

Example

To start, we can create two Scene components: RedScene and BlueScene

import { Component, viewChild, ChangeDetectionStrategy, CUSTOM_ELEMENTS_SCHEMA, ElementRef } from '@angular/core';
import { injectBeforeRender } from 'angular-three';
@Component({
template: `
<ngt-mesh #cube>
<ngt-box-geometry />
<ngt-mesh-basic-material color="red" />
</ngt-mesh>
`,
schemas: [CUSTOM_ELEMENTS_SCHEMA],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export default class RedScene {
cubeRef = viewChild.required<ElementRef<THREE.Mesh>>('cube');
constructor() {
injectBeforeRender(({ clock }) => {
this.cube().nativeElement.rotation.x = clock.elapsedTime;
this.cube().nativeElement.rotation.y = clock.elapsedTime;
});
}
}

Next, we’ll use RedScene and BlueScene in our routing configuration.

import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter } from '@angular/router';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [
provideRouter([
{
path: '',
loadComponent: () => import('./app/red-scene.component'),
},
{
path: 'blue',
loadComponent: () => import('./app/blue-scene.component'),
},
]),
],
}).catch((err) => console.error(err));

Custom routed scene

Using 'routed' will use the default NgtRoutedScene component provided by Angular Three. It is also possible to have your own routed scene component.

<ngt-canvas [sceneGraph]="CustomRoutedScene" />
@Component({
template: `
<ngt-router-outlet />
<!-- All routed scenes will have a CameraControls instead of each routed rendering their own camera controls -->
<ngts-camara-controls />
`,
imports: [
NgtRouterOutlet, // a custom router-outlet
NgtsCameraControls,
],
})
export class CustomRoutedScene {
static [ROUTED_SCENE] = true; // flag for `NgtRenderer`
}

Check out the Routed Scene demo for a better example.