36

@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{}

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

4

2 回答 2

60

您可以使用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
  }
}

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

于 2016-10-02T04:44:06.597 回答
32

要获得比 micronyks 答案更多的灵活性,您可以这样做:

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

<p #myIdentifier>
  my-component works!
</p>

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;

}

安全

关于像这样的安全风险ElementRef,没有。如果您使用 ElementRef修改DOM ,将会有风险。但是在这里你只得到DOM 元素,所以没有风险。一个危险的使用示例ElementRef是:this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser;. 像这样,Angular 没有机会使用其清理机制,因为someFunctionDefinedBySomeUser直接插入到 DOM 中,跳过了 Angular 清理。

于 2017-06-12T21:08:54.660 回答