前端编程中,经常遇到要求图片在保持宽高比的情况下,图片随窗口缩放而自动缩放,在 angular2 中我们可以用指令 Directive 实现这一功能。
首先在已有的 angular2 工程中进入要使用该功能的目录,然后在终端输入:
ng generate directive item-resize
在当前目录中会生成两个文件 item-resize.directive.ts 和 item-resize.directive.spec.ts,item-resize.directive.spec.ts 是单元测试文件我们在本文中不讨论。
用编辑器打开 item-resize.directive.ts,我用的是 VS Code,其它的也可以,输入以下代码:
import { Directive, ElementRef, HostListener, Renderer, Input, HostBinding } from '@angular/core';
@Directive({
selector: '[appItemResize]'
})
export class ItemResizeDirective {
private el: HTMLElement;
constructor(el: ElementRef, public renderer: Renderer) {
this.el = el.nativeElement;
}
@HostBinding('style.height.px')
elHeight: number;
@HostListener('window:resize', ['$event.target'])
onResize() {
this.resizeWorks();
}
// tslint:disable-next-line:use-life-cycle-interface
ngAfterViewInit() {
this.resizeWorks();
}
private resizeWorks(): void {
const elImage = this.el.getElementsByTagName('img');
const img = new Image();
const that = this;
img.src = elImage[0].src;
img.onload = function(e) {
that.elHeight = +that.el.clientWidth * img.height / img.width;
};
}
}
确认无误后保存。然后打开你当前目录中的 html 文件,我的是 introduction.component.html,在相关位置输入下面内容:
…
<div id='technology' appItemResize>
<img src="../../../../assets/images/N4Si3Patten.jpg" width="98%" style="z-index:-100;position:absolute;left:10;top:200">
</div>
…
其中 appItemResize 是我们在 item-resize.directive 中定义在指令。针对不同的图片可在文档中多处使用指令。
src 是图片文件,内容根据各自的目录结构和图片文件自行调整。
style 中的图片样式也要根据各自需要自行调整。
当然我们定义的指令要加入相应的模块文件中,如 goods.module.ts,示例代码如下:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ItemResizeDirective } from './product/introduction/item-resize.directive';
@NgModule({
declarations: [
…
ItemResizeDirective,
],
imports: [
CommonModule
],
providers: [
],
exports: [
CommonModule,
]
})
export class GoodsModule { }