angular - 如何在指令和组件中获取元素的宽度/高度?

标签 angular angular-directive angular-components

@Component({
    selector: '.donation',
    template: `
    <figure id="donation" move>
        <img src="image/qrcode.png"/>
        <figcaption>
        Buy me a cup of coffee.
        </figcaption>
    </figure>
    `
})
export class DonationComponent{}

@Directive({
    selector: '[move]'
})
export class MoveDirective{}

嘿,我想要 <figure id="donation">元素的宽度/高度在 MoveDirective 内和 DonationComponent .我已多次阅读文档,但仍然找不到解决此问题的方法。有人知道吗?非常感谢!

最佳答案

您可以使用 ElementRef 如下所示,

演示:https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview 检查浏览器的控制台。

import { Directive, Input, Output, ElementRef, Renderer } from '@angular/core';

@Directive({
  selector:"[move]",
  host:{
    '(click)':"show()"
  }
})

export class GetEleDirective{
  
  constructor(private el:ElementRef) { }

  show(){
    console.log(this.el.nativeElement);
    
    console.log('height---' + this.el.nativeElement.offsetHeight);  //<<<===here
    console.log('width---' + this.el.nativeElement.offsetWidth);    //<<<===here
  }
}

同样的方式,您可以在组件本身的任何需要的地方使用它。

关于angular - 如何在指令和组件中获取元素的宽度/高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39813269/

相关文章:

php - 多个文件上传 Angular + Laravel

angular - 跨多个 Angular 5 应用程序共享单个服务

Angular - 如何从指令访问和替换 innerHTML

angular - 从抽象类继承存在依赖注入(inject)问题

css - 在 typescript 中更改 gridready 上的 ag-grid 标题背景颜色

javascript - 无限 $digest() 循环 AngularJS,在 html 属性上使用过滤器表达式

angular - 从 Angular 2 中的历史记录中删除一个组件

angular - 如何打开作为子组件的 ng-Bootstrap-Modal?

angular - 指令绑定(bind)在规范文件中不起作用

angular - 从指令中创建/获取 TemplateRef