Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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?

like image 855
freethebees Avatar asked Dec 05 '25 16:12

freethebees


1 Answers

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
    }
}
like image 171
freethebees Avatar answered Dec 08 '25 09:12

freethebees



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!