【问题标题】:How to get element's width/height within directives and component?如何在指令和组件中获取元素的宽度/高度?
【发布时间】:2017-02-10 07:34:40
【问题描述】:

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

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

【问题讨论】:

    标签: angular angular-directive angular-components


    【解决方案1】:

    你可以如下图使用ElementRef

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

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

    【讨论】:

    • 非常感谢,它完美运行!但我仍然有点困惑为什么使用 offsetHeight 而不是 height 属性来获取元素的高度?
    • ElementRef 已被标记为安全风险:angular.io/docs/js/latest/api/core/index/ElementRef-class.html - 还可以使用吗?
    • @shiva 没有风险,因为您也在从 DOM 中提取信息,而不是插入危险元素。
    • 如果宿主元素的子元素具有比宿主更大的宽度或高度怎么办。我们如何才能获得正确的宿主元素的宽度和高度?
    • @Simon_Weaver:是的,你可以这样做,或者你也可以使用windows.resize() 事件,但谷歌它,这样你就会了解更多。
    【解决方案2】:

    要获得比 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 清理。

    【讨论】:

    猜你喜欢
    • 2019-12-29
    • 2021-10-06
    • 2019-04-11
    • 1970-01-01
    • 2018-01-12
    • 2013-08-11
    • 2017-10-02
    • 1970-01-01
    相关资源
    最近更新 更多