Angular语言 - 获取嵌套组件 html 引用



我有一个组件myComponent嵌套在一个组件中,如何从外部组件获取嵌套组件的宽度?

<div class="container">            
  <myComponent[compObj]="someObj"></myComponent>
</div>

这里需要宽度:

@Component({
})
export class OutterComponent {
  // width = myComponentHtmlRef.width
}

您可以在子组件中添加一个 getter 来获取宽度:

export class MyComponent {
  constructor(private el: ElementRef) { }
  public get width(): number {
    // Get the width however you like
    return this.el.nativeElement.getBoundingClientRect().width;
  }
}

然后在父组件中访问该组件的 getter:

export class OuterComponent {
  @ViewChild(MyComponent) child: MyComponent;
  ngAfterViewInit() {
    let width = this.child.width;
  }
}

我将创建一个通用指令,该指令将元素宽度作为表达式公开给模板。您可以稍后重复使用它,因为您将再次遇到问题。

@Directive({
    selector: 'on-width'
})
export class OnWidthDirective implements DoCheck {
   @Output('on-width')
   public widths: EventEmitter<number> = new EventEmitter();
   private _lastWidth: number;
   public constructor(private el: ElementRef) {}
   public ngDoCheck(): void {
      const w = this.el.nativeElement.getBoundingClientRect().width;
      if(this._lastWidth !== w) {
          this.widths.next(w);
          this._lastWidth = w;
      }
   }
}

现在,在OutterComponent的模板中,您可以侦听任何模板元素上的宽度变化。

@Component({
    template: '<child-thing (on-width)="onWidth($event)"></child-thing>'
})
export class OuterComponent {
    public onWidth(width: number) {
       console.log(width); // called when child resizes
    }
}

最新更新