簡體   English   中英

錯誤TypeError:無法讀取未定義的屬性“nativeElement”

[英]ERROR TypeError: Cannot read property 'nativeElement' of undefined

我是角度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);

}
}

我有錯誤

錯誤TypeError:無法讀取未定義的屬性“nativeElement”

請幫我解決這個問題

謝謝

制作layout本地模板變量

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

工作演示

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM