Scandinave Scandinave - 4 years ago 109
Javascript Question

How to use ContentChild annotation in Angular2

I try to make my own component that needs to have reference to a child element define by user.

In my html template i have this :

<fn-photo-editor fxLayout="row" fxLayoutGap="20px" class="coloredContainerX box">
<div"80" fxFlex="33" fxLayout="row" fxLayoutAlign="center center">
<canvas fnPhotoEditorCanvas height="1080px" width="1920px" fxFlex dropzone="copy"></canvas>

In my Component.ts I have this :

@ContentChild(FnPhotoEditorCanvasDirective) canvas:HTMLCanvasElement;

and in my component template, just :


I use this directive on the canvas to get it's reference, since just using @ContentChild('canvas') seems to not work.

selector: '[fnPhotoEditorCanvas]',
export class FnPhotoEditorCanvasDirective { }

So its this code, i get a reference to a FnPhotoEditorCanvasDirective object but it does not contains or represent a canvas object.

What i'm missing?

Answer Source

@ContentChild('canvas') works only if the element has a template variable #canvas

<canvas #canvas fnPhotoEditorCanvas height="1080px" width="1920px" fxFlex dropzone="copy"></canvas>

This query

@ContentChild(FnPhotoEditorCanvasDirective) canvas:HTMLCanvasElement;

will return the instance of the FnPhotoEditorCanvasDirective, not a HTMLCanvasElement.

Perhaps you want

@ContentChild(FnPhotoEditorCanvasDirective, {read: ElementRef}) canvas:HTMLCanvasElement;

then you can access the HTMLCanvasElement like

ngAfterContentInit() {

See also angular 2 / typescript : get hold of an element in the template

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download