本文介绍了如何在指令和组件中获取元素的宽度/高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
@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 the <figure id="donation">
element's width/height within MoveDirective
and DonationComponent
. I have read the documentation several times but still cannot find a way to this answer. Does somebody know this? Thanks a lot!
推荐答案
可以使用ElementRef如下图,
演示:https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=预览检查浏览器的控制台.
DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.
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
}
}
同样,您可以在任何需要的地方在组件中使用它.
Same way you can use it within component itself wherever you need it.
这篇关于如何在指令和组件中获取元素的宽度/高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!