Angular 和离子组件中的 clientHeight 和 clientWidth 始终为零

clientHeight & clientWidth always zero in Angular & Ionic Component

我有条形码组件,使用时它应该以正确的宽度和高度(容器的宽度和高度)显示条形码扫描器。正确初始化扫描仪需要这些值。

我想在 angular 中使用 ElementReference 获取 clientHeight 和 clientWidth。像这样:

@ViewChild('scannercontainer') scannerContainer: ElementRef;

ngAfterViewInit() {
    console.log('Container clientHeight: ', this.scannerContainer.nativeElement.clientHeight);
    console.log('Container clientWidth: ', this.scannerContainer.nativeElement.clientWidth);
}

Html:

<div class="viewport-wrapper" #scannercontainer>
    <div [hidden]="!scannerInitialized" class="viewport" #scanner></div>
</div>

SCSS:

$card-padding: 20px;
$card-border-radius: 6px;
$card-background-color: #ffffff;

:host {
    display: block;
    width: 100%;
    height: 250px;
}


::ng-deep .viewport-wrapper {
    display:block;
    width: 100%;
    height: 250px; // height: 100%;
    border-bottom-left-radius: $card-border-radius;
    border-bottom-right-radius: $card-border-radius;
    overflow: hidden;
    position: relative;
    .viewport {
        display:block;
        canvas {
            position:absolute;
            top: 0;
            left: 0;
        }
    }
}

当我检查控制台日志时,clientHeight 和 clientWidth 始终为零,因此我尝试使用 setTimeout() 添加超时;方法。这有效,但前提是我等了 3 秒。零无效。

我可以使用其他解决方案吗?

我尝试将条形码组件源直接放入我计划使用它的页面中。这工作正常,但我真的很好奇为什么这行不通。

为了获得从模板到组件的高度,您可以使用@ViewChild()... 完整的工作示例在此 StackBlitz Link

// your HTML file is..

<div style="width:50vw; margin: 0 auto; border: 1px solid red; padding:1rem; text-align:center" #barcode>

     <app-barcode [ObjectHeight]="barcodeHeight" >
     </app-barcode>
</div>

// 你的 Component.ts 是 ...

@ViewChild ('barcode', {static:true}) barcode : ElementRef;

   constructor(private cdr: ChangeDetectorRef){}

ngAfterViewInit(){
   this.barcodeHeight= this.barcode.nativeElement.clientHeight;
   this.cdr.detectChanges();
}

// 您的条形码 Component.ts 是...

 height;
  @Input ('ObjectHeight') set heightFromApp(value){
    this.height= value;
  }