【问题标题】:ERROR TypeError: Cannot read property 'nativeElement' of undefined错误类型错误:无法读取未定义的属性“nativeElement”
【发布时间】:2018-07-18 15:21:17
【问题描述】:

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

}
}

我有错误

ERROR TypeError: Cannot read property 'nativeElement' of undefined

请帮我解决这个问题

谢谢

【问题讨论】:

    标签: html angular typescript html5-canvas


    【解决方案1】:

    制作layout局部模板变量

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

    WORKING DEMO

    【讨论】:

    • 先生错误已修复。 strokeRect 也可以,但我的图片没有显示在那里
    • 查看图片路径
    • this.context.drawImage(this.image,20,20,500,260);这个有问题吗
    • 没问题你可以查看demo app
    • 先生,您的 src google 图片一切正常,但我的图片 src 路径不正确先生,我仍在努力。我在 assets/images 文件夹中的图像,但仍然无法正常工作
    【解决方案2】:

    随着 Angular 8 的更新,ViewChild 略有变化,您可以通过以下代码 sn-p 了解它的工作原理:

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

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2018-02-26
      • 2018-11-21
      • 2018-11-15
      • 1970-01-01
      • 2018-04-29
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      相关资源
      最近更新 更多