0
我有一个简单的要求来显示给定的图像URI的尺寸原始。像这样非常简单的东西。如何在Angular 2模板中显示原始图像尺寸?
<div><img src="{{imageUri}}"/></div>
<p>Image size: {{width}}x{{height}}</p>
我正在使用异步方法来获取图像尺寸listening for the "load" event。但在事件处理程序中,我如何更新UI?
我试过简单地在我的组件中设置this.width
和this.height
,它实现了OnInit
。下面的代码片段说明了我正在尝试做什么,并且我还创建了一个more complete plunk来演示此问题。
constructor() {
this.imageUri = 'https://angular.io/resources/images/logos/angular2/angular.svg';
this.width = 0;
this.height = 0;
}
handleImageLoad(event): void {
this.width = event.target.width;
this.height = event.target.height;
}
ngOnInit(): void {
this.version = 2; // Just to prove Angular is working
// Set the image height and width
var image = new Image();
image.addEventListener('load', this.handleImageLoad);
image.src = this.imageUri;
}
我觉得有一个非常简单的解决方案,我的思念,或角2一些信条,我无意中侵犯。
这是不可思议的,yurzui。我不知道这是为什么会起作用,但它确实有效,我会在后面找出原因。谢谢! –
你可以看一下文档https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_this – yurzui