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

胡亚雄*_*胡亚雄 18 angular-directive angular-components angular

@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{}
Run Code Online (Sandbox Code Playgroud)

嘿,我想在MoveDirective和DonationComponent中获取元素的宽度/高度,我多次阅读文档但仍无法找到解决这个问题的方法.有人知道这个请帮帮我,非常感谢!

mic*_*yks 40

您可以使用ElementRef,如下所示,

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

import { Directive,Input,Outpu,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
  }
}
Run Code Online (Sandbox Code Playgroud)

同样,您可以在组件本身的任何地方使用它.

  • 非常感谢,它完美无缺!但我仍然有点困惑为什么使用 offsetHeight 而不是 height 属性来获取元素的高度? (3认同)
  • `ElementRef` 已被标记为安全风险:https://angular.io/docs/js/latest/api/core/index/ElementRef-class.html - 仍然可以使用它吗? (3认同)

ber*_*ing 14

为了比使用micryks答案更灵活一点,您可以这样做:

1.在模板中,添加#myIdentifier要从中获取宽度的元素.例:

<p #myIdentifier>
  my-component works!
</p>
Run Code Online (Sandbox Code Playgroud)

2.在控制器中,您可以使用它@ViewChild('myIdentifier')来获取宽度:

import {AfterViewInit, Component, ElementRef, OnInit, ViewChild} from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss']
})
export class MyComponentComponent implements AfterViewInit {

  constructor() { }

  ngAfterViewInit() {
    console.log(this.myIdentifier.nativeElement.offsetWidth);
  }

  @ViewChild('myIdentifier')
  myIdentifier: ElementRef;

}
Run Code Online (Sandbox Code Playgroud)

安全

关于安全风险ElementRef,像这样,没有.如果您使用ElementRef 修改 DOM ,则存在风险.但是在这里你只获得 DOM Elements,所以没有风险.一个冒险的使用例子ElementRef是:this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser;.像这样的角度没有得到一个机会,因为使用它的禁制机制someFunctionDefinedBySomeUser插入直接到DOM,跳过的角度环境卫生.

  • 试图按照您的示例进行操作,但“this.myIdentifier”返回未定义... (3认同)