首页 > 解决方案 > 从父组件获取角度子组件的 offsetHeight

问题描述

从父级获取计算的角度子组件高度的最佳方法是什么?我有一个像下面这样的组件

    import { Component, ViewChild } from 'angular2/core';  

    (...)

    @Component({
      selector: 'my-app',
      template: `
        <h1>My Add Angular 8 app</h1>
       <ng-container *ngFor="let item of list>
          <child #Children [content]="item.content" [id]="id"></child>
       <ng-container>
        <button (click)="submit()">Submit</button>
      `,
    })
    export class AppComponent implements AfterViewInit { 
      @ViewChild(Children) Children: QueryList<ElementRef>;

      (...)
      ngAfterViewInit() {
        console.log("The children are", this.Children.toArray()) 
        /*==> give me aray of Child component with the props , id and content, 
        i need the computer nativeElement to be able to get the height. */
      }

    }

请问从父组件获取子组件 offsetHeight 的最佳方法是什么?任何帮助将不胜感激

标签: angular

解决方案


您可以将读取元数据属性设置为 ElementRef 以获取子元素的偏移量

尝试这个:

 @ViewChildren('Children',{read:ElementRef}) Children: QueryList<ElementRef>;

或者

您在子组件中有 Inject ElementRef 服务,以便您可以在父组件中添加子组件 nativeElement

child.component.html

 constructor(public ele: ElementRef){

  }

父组件.html

@ViewChildren('Children') Children: QueryList<ChildComponent>;

   ngAfterViewInit(){ 
    console.log(this.Children.toArray()[0].ele.nativeElement.offsetTop);
   }

例子


推荐阅读