freethebees
freethebees

Reputation: 1017

How to render HTML element that is a variable in an Angular 2 component

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?

Upvotes: 3

Views: 2955

Answers (1)

freethebees
freethebees

Reputation: 1017

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
    }
}

Upvotes: 2

Related Questions