angualr2 中用指令Directive实现图片尺寸随窗口尺寸而改变

前端编程中,经常遇到要求图片在保持宽高比的情况下,图片随窗口缩放而自动缩放,在 angular2 中我们可以用指令 Directive 实现这一功能。

首先在已有的 angular2 工程中进入要使用该功能的目录,然后在终端输入:

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-interfacengAfterViewInit() {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,在相关位置输入下面内容: 

其中 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 { }

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部