@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/