我正在尝试在验证后将一些图像信息发送到模板。但是我没有。

转到模板的变量在回调中,或者在异步函数中,并且我不知道将此信息发送到模板。

能帮我解决这个问题吗?我已经尝试了一切。

event.component.ts

import "rxjs/Rx";
import {Component} from '@angular/core';

@Component({
    selector: '<my-image></my-image>',
    templateUrl: './event.component.html',
})
export class EventComponent {
    files: File[];
    file: any
    imageName: any;
    imageSize: any;
    whithImage = false;

    ngOnInit() {this.files = []}

    onFileSelect(event) {
        this.files = event.dataTransfer ? event.dataTransfer.files : event.target.files;
        this.file = this.files[0];
        this.isImage(this.file, function(res, file){
            if(res==true){
                this.imageName = file.name;
                this.imageSize = file.size;
                this.whithImage = res;
            }
        })
    }

    isImage(file, callback) {
        var reader = new FileReader();
        reader.onload = function(event) {
            var contents = reader.result;
            var buf = new Uint8Array(contents);
            if(buf[0] === 0xFF && buf[1] === 0xD8 && buf[2] === 0xFF){
                callback(true, file) //jpg
            }else{callback(false)}
        };
        reader.readAsArrayBuffer(file);
    }

    onChooseClick(event, fileInput) {
        fileInput.value = null;
    }


event.component.html

<span (click)="onChooseClick($event, fileinput)">
    Image<input  #fileinput type="file" (change)="onFileSelect($event)"/>
</button>
<div *ngIf="whithImage">
    <p>{{ imageName }}</p>
    <p>{{ imageSize }}</p>
</div>

最佳答案

尝试@peeskillet首先建议的内容-即通过使用arrow function使用正确的this上下文:

export class EventComponent {
   onFileSelect(event) {
        ...
        this.isImage(this.file, (res, file) => {     // <----
            if(res==true) {
                this.imageName = file.name;
                this.imageSize = file.size;
                this.whithImage = res;
            }
        });
    }


如果这不起作用,则Angular不会知道如何猴子化您的异步事件,因此,当事件触发时,Angular更改检测将不会运行(因此您的视图不会更新以反映新的组件属性值) 。您需要manually trigger change detection。这是一种实现方法:

import {ChangeDetectorRef} from '@angular/core';     // <-----
export class EventComponent {
   constructor(private cdref:ChangeDetectorRef) {}   // <-----
   onFileSelect(event) {
        ...
        this.isImage(this.file, (res, file) => {     // <----
            if(res==true) {
                this.imageName = file.name;
                this.imageSize = file.size;
                this.whithImage = res;
                this.cdref.detectChanges();          //  <------
            }
        });
    }

09-12 21:03