【问题标题】:get offsetHeight of angular child component from parent从父组件获取角度子组件的 offsetHeight
【发布时间】:2020-05-14 14:52:35
【问题描述】:

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

    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


    【解决方案1】:

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

    试试这个:

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

    或者

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

    child.component.html

     constructor(public ele: ElementRef){
    
      }
    

    parent.component.html

    @ViewChildren('Children') Children: QueryList<ChildComponent>;
    
       ngAfterViewInit(){ 
        console.log(this.Children.toArray()[0].ele.nativeElement.offsetTop);
       }
    

    Example

    【讨论】:

    • 感谢您的帮助。虽然它返回 nativeElement,但高度和宽度始终为 0。还有什么我想念的吗?
    • 设置子元素宿主显示:block
    • 样式:[:host { display: block }]
    • 谢谢。虽然我可以看到你的作品,但我尝试了一切,但我的没有奏效。它总是 0。
    • 你创建了stackblitz的出租车?
    猜你喜欢
    • 2023-04-09
    • 2022-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多