2016-10-02 72 views
7

如何在指令和組件中獲取元素的寬度/高度?

@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元素的寬度/高度,我閱讀該文檔幾次,但仍然無法找到一種方法,這種answer.Do有人知道這個請幫助我,非常感謝!

回答

18

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

DEMO: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 
    } 
} 

同樣的方式,你可以在任何需要它的組件中使用它。

+1

非常感謝,它工作完美!但我仍然有點困惑,爲什麼使用offsetHeight而不是高度屬性來獲取元素的高度? –

+0

'ElementRef'已被標記爲安全風險:https://angular.io/docs/js/latest/api/core/index/ElementRef-class.html - 使用它仍然可以嗎? – shiva

+0

@shiva不存在風險,因爲您也從DOM中提取信息,而不是插入危險元素。 – bersling

6

對於位比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將修改爲 DOM,將會存在風險。但在這裏你只有得到 DOM元素,所以沒有風險。使用ElementRef的一個有風險的例子是:this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser;。像這樣Angular沒有機會使用其清潔機制,因爲someFunctionDefinedBySomeUser被插入直接進入DOM,跳過角衛生化。

+0

這個句柄如何調整事件大小? –

+1

它沒有,但您可以添加@HostListener窗口:調整大小,請參閱https://開頭威士忌。IO /教程/響應相等,高度與-角指令#TOC-WAIT-是 - 我們 - 做 - 但 – bersling

相關問題