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

在前端开发中,为保持图片宽高比并使其随窗口缩放,可以使用 Angular2 的 Directive 功能。通过创建并应用自定义指令 item-resize.directive.ts,设置图片样式并在 HTML 中绑定指令,实现图片尺寸的动态调整。首先在 Angular2 工程中生成并编写指令文件,然后在组件模板中引入并应用该指令,最后将指令添加到对应模块。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前端编程中,经常遇到要求图片在保持宽高比的情况下,图片随窗口缩放而自动缩放,在 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 { }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值