3

I want to have a component that renders an arbitrary number of canvas elements that contain images or videos or whatever. Sometimes there will be one image. Other times I'll want to have two or three side-by-side. Maybe there's a button to toggle between one or two images.

So my component looks roughly like this:

@Component({
    selector: 'canvas-container',
    template: `<div *ngFor="let canvas of canvases">???</div>`
})
export class CanvasContainerComponent {

    canvases: HTMLCanvasElement[] = [];

    addCanvas(image) {
        const canvas = <HTMLCanvasElement> document.createElement('canvas');
        // some stuff to do with sizing and drawing
        this.canvases.push(canvas);
    }
}

So another component will call the addCanvas method, or the canvases will be passed in as an @Input.

How can I wrestle with Angular 2 to then render these canvases that are stored as HTMLCanvasElement variables? Using {{canvas}} just displays the string form of the element: [object HTMLCanvasElement].

Or is there a better way to approach this whole endeavour?

1 Answer 1

2

Instead of <div *ngFor="let canvas of canvases">...</div>, you can simply use <canvas myCanvasDirective *ngFor="let canvas of canvases" [inputs ...]></canvas>. Then you can write a directive that deals with how to render each canvas based on the inputs you send in.

import { Directive, ElementRef } from '@angular/core';

@Directive({ selector: '[myCanvasDirective]' })
export class MyCanvasDirective {
    constructor(el: ElementRef) {
        const canvas: HTMLCanvasElement = el.nativeElement;
        // Do all the canvas context and drawing stuff here
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.