2016-03-22 25 views
11

Tamamlayıcı sınıfın (TypeScript kodu) içindeki bir Input() özelliği ile yeniden boyutlandırdığım bir kanvasa dayalı basit bir bileşen yazdım. Yapmak istediğim, tuval elemanını, kodu aşağıdakinde bulunan tamamlayıcı sınıfın içinde çizmek. Bunu başarmanın en kolay yolu nedir? (Lütfen koddaki yorumu görün: Oluşturucunun tuvalinde mavi bir dikdörtgen çizmek istiyorum).Tuvale dayalı Angular2 bileşeni: İçerisinde nasıl çizilir?

import {Component, View, Input} from 'angular2/core'; 

@Component({ 
    selector: 'chess-diagram', 
}) 
@View({ 
    template: `<canvas class='chess-diag' 
    [attr.width]='_size' 
    [attr.height]='_size'></canvas>`, 
}) 
export class ChessDiagram { 
    private _size: number; 

    constructor(){ 
     this._size = 150; 
     // Here I would like to draw a blue rectangle inside the canvas. 
    } 

    get size(){ 
     return this._size; 
    } 

    @Input() set size(newValue: number){ 
     this._size = Math.floor(newValue); 
    } 
} 

cevap

22

Sen tuval elemanının bir örneğini kapmak için ViewChild ek açıklama kullanabilirsiniz. Bundan sonra hepsi vanilya js.

import {Component, View, Input, ViewChild, ElementRef} from 'angular2/core'; 

@Component({ 
    selector: 'chess-diagram', 
}) 
@View({ 
    template: `<canvas #chessCanvas class='chess-diag' 
    [attr.width]='_size' 
    [attr.height]='_size'></canvas>`, 
}) 
export class ChessDiagram { 
    private _size: number; 

    // get the element with the #chessCanvas on it 
    @ViewChild("chessCanvas") chessCanvas: ElementRef; 

    constructor(){ 
     this._size = 150; 
    } 

    ngAfterViewInit() { // wait for the view to init before using the element 

     let context: CanvasRenderingContext2D = this.chessCanvas.nativeElement.getContext("2d"); 
     // happy drawing from here on 
     context.fillStyle = 'blue'; 
     context.fillRect(10, 10, 150, 150); 
    } 

    get size(){ 
     return this._size; 
    } 

    @Input() set size(newValue: number){ 
     this._size = Math.floor(newValue); 
    } 
} 

bir ElementRef aralarından yerli tuval eleman alabilirsiniz dönecektir @ViewChild olduğunu nativeElement özelliğini kullanarak.

+0

Cevabınız için teşekkür ederiz. Ama chessCanvas değişkenini tanımsız olarak alıyorum. NgAfterViewInit içinde – loloof64

+0

bir yerlerde bir yazım hatası olabilir. Bir bileşen kurarım ve çalışıp çalışmadığını kontrol edeceğim. :) – toskv

+0

Teşekkür ederim, ben de bulmaya çalışıyorum. – loloof64