1

我有一个组件(标注气泡),它需要根据其原生元素大小来计算它的位置。默认情况下它是隐藏的,因此元素没有大小。

当我将隐藏绑定更改为 false 时,我在哪里挂钩事件,我可以在渲染后测量原生元素的大小?

@Component({
  selector: 'app-callout',
  template: `<div #content class="callout-content">
    <div class="callout-header">
      <div class="title">{{title}}</div>
    </div>
    <div style="height: 100%; flex:1">
      <ng-content></ng-content>
    </div>
  </div>`
})
export class CalloutComponent {
  @HostBinding('hidden')
  @Input()
  isHidden:boolean = false;
  @ViewChild('content') content: ElementRef<HTMLDivElement>

  ngAfterViewChecked(){
    //called after isHidden is changed, but
    //NOT OK: content.nativeElement.offsetWidth == 0;

    setTimeout(() => {
      // OK: content.nativeElement.offsetWidth == 100;
      // but I would like to get rid of this timer workaround

    }, 100);
  }

  show(){
    this.isHidden = false;
  }
}
4

0 回答 0