How to get element's width/height within directives and component?

后端 未结 2 844
故里飘歌
故里飘歌 2021-02-02 09:34



        
2条回答
  •  醉酒成梦
    2021-02-02 09:55

    For a bit more flexibility than with micronyks answer, you can do it like that:

    1. In your template, add #myIdentifier to the element you want to obtain the width from. Example:

    my-component works!

    2. In your controller, you can use this with @ViewChild('myIdentifier') to get the width:

    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;
    
    }
    

    Security

    About the security risk with ElementRef, like this, there is none. There would be a risk, if you would modify the DOM using an ElementRef. But here you are only getting DOM Elements so there is no risk. A risky example of using ElementRef would be: this.myIdentifier.nativeElement.onclick = someFunctionDefinedBySomeUser;. Like this Angular doesn't get a chance to use its sanitisation mechanisms since someFunctionDefinedBySomeUser is inserted directly into the DOM, skipping the Angular sanitisation.

提交回复
热议问题