错误TypeError:无法读取未定义的属性“nativeElement”

时间:2018-02-08 06:29:27

标签: html5 angular typescript html5-canvas

我是角度2的新手,我在图像裁剪插件上工作,我想在画布上显示图像。 这里是我的HTML代码

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

这是我的打字稿文件

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);

}
}

我有错误

错误类型错误:无法读取未定义的属性“nativeElement”

请帮我解决这个问题

谢谢

2 个答案:

答案 0 :(得分:2)

制作layout本地模板变量

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

<强> WORKING DEMO

答案 1 :(得分:0)

通过对Angular 8的更新,ViewChild进行了少许更改,您可以从以下代码片段中了解它的工作原理:

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

使用Renderer2(无需直接访问DOM),操作如下:

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