Skip to content

Extending Functionality with Directives

Angular Three elements are like regular DOM elements; they are just rendered to the Canvas instead of the DOM. With that in mind, we can extend the functionality of Angular Three elements by using Directives like we do with regular DOM elements.

Attribute Directives in Angular

When we attach an Attribute Directive to an element, we have access to the element’s host instance via ElementRef token. Angular Three elements return the actual THREE.js entity instance as the host instance so that we can access the THREE.js APIs to extend the functionality of the element.

Build a cursor Directive

Let’s build a cursor directive that will change the cursor to a pointer when the element is hovered.

1
@Directive({selector: '[cursor]', standalone: true})
2
export class Cursor {
3
constructor() {
4
5
const elementRef = inject<ElementRef<Object3D>>(ElementRef);
6
const nativeElement = elementRef.nativeElement;
7
8
if (!nativeElement.isObject3D) return;
9
10
const localState = getLocalState(nativeElement);
11
if (!localState) return;
12
13
const document = inject(DOCUMENT);
14
15
injectObjectEvents(() => nativeElement, {
16
pointerover: () => {
17
document.body.style.cursor = 'pointer';
18
},
19
pointerout: () => {
20
document.body.style.cursor = 'default';
21
},
22
});
23
}
24
}

Now, we can use the cursor directive on any element to change the cursor to a pointer when the element is hovered.

1
<ngt-mesh cursor (pointerover)="hovered.set(true)" (pointerout)="hovered.set(false)">
2
<ngt-box-geometry />
3
<ngt-mesh-standard-material [color]="hovered() ? 'mediumpurple' : 'maroon'" />
4
</ngt-mesh>