1

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 fxFlex.gt-sm="80" fxFlex="33" fxLayout="row" fxLayoutAlign="center center">
          <canvas fnPhotoEditorCanvas height="1080px" width="1920px" fxFlex dropzone="copy"></canvas>
    </div>
</fn-photo-editor>

In my Component.ts I have this :

@ContentChild(FnPhotoEditorCanvasDirective) canvas:HTMLCanvasElement;

and in my component template, just :

<ng-content></ng-content>

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

@Directive({
   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?

Scandinave
  • 1,388
  • 1
  • 17
  • 41

1 Answers1

1

@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() {
  this.canvas.nativeElement...
}

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

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567