Docs · OSMD 3.0
OSMD in Angular
A standalone component with a signal input. An afterRenderEffect creates OSMD once the view exists, loads and renders, and destroys it in its cleanup.
import { Component, ElementRef, afterRenderEffect, input, viewChild } from '@angular/core';
import { OpenSheetMusicDisplay } from 'opensheetmusicdisplay';
@Component({
selector: 'score-view',
template: '<div #container></div>',
})
export class ScoreView {
readonly url = input.required<string>();
private readonly container = viewChild.required<ElementRef<HTMLDivElement>>('container');
constructor() {
afterRenderEffect((onCleanup) => {
const osmd = new OpenSheetMusicDisplay(this.container().nativeElement);
osmd
.load(this.url())
.then(() => osmd.render())
.catch((error: Error) => {
// AbortError: url changed, or the component was destroyed, before the file arrived
if (error.name !== 'AbortError') console.error(error);
});
onCleanup(() => osmd.destroy());
});
}
}
Add ScoreView to the imports of the component that uses it, then: <score-view url="/scores/my-score.musicxml" />.
afterRenderEffect runs after Angular has rendered the view, so the #container element is there. It runs again when url() changes; the function given to onCleanup runs before that and when the component is destroyed. After-render effects don’t run during server-side rendering, so OSMD only runs in the browser.
What destroy() does
osmd.destroy() is new in OSMD 3.0. It aborts a load() still in flight, releases the loaded score, removes OSMD’s resize observer, takes OSMD’s pages and cursor out of the element and ends the instance. Our CI compiles this component ahead of time with Angular’s own compiler, strict and with strict template checks, then shows a score, switches to a second one and destroys the component, and checks that every OSMD instance it made is destroyed and no OSMD element is left on the page.
A url that changes while a file is still loading destroys that instance before the file arrives: its load() is rejected with an AbortError, which the catch lets pass.
Resizing
With autoResize on (the default), OSMD 3.0 watches the element’s width with a ResizeObserver and lays the score out again 200 ms after the width stopped changing. Height changes, like a phone’s address bar sliding in and out, don’t redraw the score. A render() while the element is hidden (a tab that isn’t shown, display: none) is skipped, and the score is drawn once the element has a width.
On OSMD 2.3.1
Before 3.0 there is no destroy(). On 2.3.1, dispose() comes closest: it removes OSMD’s listeners, but leaves the drawing in the element.
Next: OSMD in Svelte