将两个元素设置为相同的高度

时间:2019-03-28 00:08:02

标签: angular ionic-framework ionic4

我尝试将一个元素设置为与另一个元素相同的高度,并且使用*ngIf指令有条件地显示后一个元素:

<!-- HTML code -->
<my-custom-component #notificationBar *ngIf="notificationMessage">
</my-custom-component>

<ion-content>
  <div style="background: red; width: 100%;"
    [style.height]="notificationBar && notificationBar.nativeElement.offsetHeight">
  </div>
  <!-- .... -->
</ion-content>


//*.ts code
@ViewChild("notificationBar") notificationBar: ElementRef;

我面临的问题是显示自定义组件时出现ExpressionChangedAfterItHasBeenCheckedError错误:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'height: undefined'. Current value: 'height: 0'.

还有其他合适的方法将两个元素设置为相同的高度吗?

谢谢

1 个答案:

答案 0 :(得分:2)

可以在属性获取器的帮助下获取通知栏的高度。当高度改变时,调用ChangeDetectorRef.detectChanges以避免将高度应用于div元素时发生的异常。

@ViewChild("notificationBar") private notificationBarRef: ElementRef<HTMLElement>;

private _notificationBarHeight: number = null;

public get notificationBarHeight(): number {
  const height = this.notificationBarRef ? this.notificationBarRef.nativeElement.offsetHeight : null;
  if (Math.abs(height - this._notificationBarHeight) > 0.1) {
    this._notificationBarHeight = height;
    this.changeDetectorRef.detectChanges();
  }
  return this._notificationBarHeight;
}

在模板中,使用div绑定设置[style.height.px]元素的高度(以像素为单位):

<div ... [style.height.px]="notificationBarHeight">
</div>

有关演示,请参见cumcount