kittencup / angular2-ama-cn

angular2 随便问
691 stars 101 forks source link

Angular 2 中有没类似ng1中scope.$apply()强制触发变化检测的方法吗? #126

Open kittencup opened 8 years ago

kittencup commented 8 years ago

问题来源于 https://github.com/kittencup/angular2-ama-cn/issues/123#issuecomment-198218926

kittencup commented 8 years ago

可使用 changeDetectorRef.detectChanges(); 来强制触发change detection

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

@Component({
    selector: 'app',
    template: `
        <h1>app</h1>
        <canvas #canvas [width]="width" height="height"></canvas>
  `,
})
export class App {

    @ViewChild('canvas') canvas: ElementRef;
    context: CanvasRenderingContext2D = null;
    width:number = 0;
    height:number = 0;

    constructor(public changeDetectorRef: ChangeDetectorRef){

    }
    ngAfterViewInit(){
        this.context = this.canvas.nativeElement.getContext('2d');

        let img = new Image();

        img.onload =  () => {
            this.width = img.width;
            this.height = img.height;

            this.changeDetectorRef.detectChanges();
            this.context.drawImage(img, 0, 0);
        };

        img.src = 'https://www.google.co.jp/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
    }
}