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.
1<ngt-canvas sceneGraph="routed" />
Example
To start, we can create two Scene components: RedScene
and BlueScene
1import { Component, viewChild, ChangeDetectionStrategy, CUSTOM_ELEMENTS_SCHEMA, ElementRef } from '@angular/core';2import { injectBeforeRender } from 'angular-three';3
4@Component({5 standalone: true,6 template: `7 <ngt-mesh #cube>8 <ngt-box-geometry />9 <ngt-mesh-basic-material color="red" />10 </ngt-mesh>11 `,12 schemas: [CUSTOM_ELEMENTS_SCHEMA],13 changeDetection: ChangeDetectionStrategy.OnPush,14})15export default class RedScene {16 cubeRef = viewChild.required<ElementRef<THREE.Mesh>>('cube');17
18 constructor() {19 injectBeforeRender(({ clock }) => {20 this.cube().nativeElement.rotation.x = clock.elapsedTime;21 this.cube().nativeElement.rotation.y = clock.elapsedTime;22 });23 }24}
1import { Component, viewChild, ChangeDetectionStrategy, CUSTOM_ELEMENTS_SCHEMA, ElementRef } from '@angular/core';2import { injectBeforeRender } from 'angular-three';3
4@Component({5 standalone: true,6 template: `7 <ngt-mesh #cube>8 <ngt-box-geometry />9 <ngt-mesh-basic-material color="blue" />10 </ngt-mesh>11 `,12 schemas: [CUSTOM_ELEMENTS_SCHEMA],13 changeDetection: ChangeDetectionStrategy.OnPush,14})15export default class BlueScene {16 cubeRef = viewChild.required<ElementRef<THREE.Mesh>>('cube');17
18 constructor() {19 injectBeforeRender(({ clock }) => {20 this.cube().nativeElement.rotation.x = clock.elapsedTime;21 this.cube().nativeElement.rotation.y = clock.elapsedTime;22 });23 }24}
Next, we’ll use RedScene
and BlueScene
in our routing configuration.
1import { bootstrapApplication } from '@angular/platform-browser';2import { provideRouter } from '@angular/router';3import { AppComponent } from './app/app.component';4
5bootstrapApplication(AppComponent, {6 providers: [7 provideRouter([8 {9 path: '',10 loadComponent: () => import('./app/red-scene.component'),11 },12 {13 path: 'blue',14 loadComponent: () => import('./app/blue-scene.component'),15 },16 ]),17 ],18}).catch((err) => console.error(err));