本文介绍了如何在指令和组件中获取元素的宽度/高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
@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{}
嘿,我想在MoveDirective和DonationComponent中获取元素的宽度/高度,我多次阅读了文档,但仍然找不到解决这个问题的方法.有人知道这一点对我有帮助吗,非常感谢!
Hey,I want to get element's width/height within MoveDirective and DonationComponent,I read the document several times but still can not find a way to this answer.Do somebody know this please help me,thanks a lot!
推荐答案
您可以如下所示使用 ElementRef ,
演示: https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview .检查浏览器的控制台.
DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.
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
}
}
以同样的方式可以在组件中随处使用它.
Same way you can use it within component itself wherever you need it.
这篇关于如何在指令和组件中获取元素的宽度/高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!