Sachith Nanayakkara
Sachith Nanayakkara

Reputation: 155

ERROR TypeError: Cannot read property 'nativeElement' of undefined

i am new to angular 2 and i work on image cropping plugin and i want to display the image on canvas. here my html code

<div class="row">
  <div class="col-sm-6">
     <canvas id="layout" width="400" height="300">
        This text is displayed if your browser does not support HTML5 Canvas.
     </canvas>

and here is my typescript file

import { Component, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-four',
templateUrl: './four.component.html',
styleUrls: ['./four.component.css']
})
export class FourComponent implements OnInit {
image: HTMLImageElement;
profPic: any;
context: CanvasRenderingContext2D;

constructor() { }
@ViewChild('layout') canvas;
@ViewChild('photo') photo;

ngOnInit() {
const _canvas = this.canvas.nativeElement;
//let photo = this.photo.nativeElement;
this.context = (<HTMLCanvasElement>_canvas).getContext('2d');
  this.image = new Image();
  this.image.src = '../../assets/images/1.jpg';

this.context.drawImage(this.image,20,20,500,260);

}
}

and i have error

ERROR TypeError: Cannot read property 'nativeElement' of undefined

please help me to fix this

thank you

Upvotes: 3

Views: 3951

Answers (2)

Daniel Danielecki
Daniel Danielecki

Reputation: 10502

With the update to Angular 8 the ViewChild changed slightly, you can get taste how it does works from the following code snippet:

@Component({
  template: `
    <div *ngIf="showMe" #viewMe>Am I here?</div>
    <button (click)="showMe = !showMe"></button>
  ` 
})
export class ExampleComponent {
  @ViewChild('viewMe', { static: false })
  viewMe?: ElementRef<HTMLElement>; 

  showMe = false;
}

With a Renderer2 (without accessing DOM directly) it would go as follows:

constructor(private renderer:Renderer2) {}

@ViewChild('one') d1:ElementRef;

ngAfterViewInit() {
  const d2 = this.renderer.createElement('div');
  const text = this.renderer.createText('two');
  this.renderer.appendChild(d2, text);
  this.renderer.appendChild(this.d1.nativeElement, d2);
}

Upvotes: 0

santosh singh
santosh singh

Reputation: 28642

Make layout local template variable

 <canvas #layout id="layout" width="400" height="300">
        This text is displayed if your browser does not support HTML5 Canvas.
     </canvas>

WORKING DEMO

Upvotes: 3

Related Questions