【问题标题】:How to set condition in ngstyle or ngclass如何在 ngstyle 或 ngclass 中设置条件
【发布时间】:2020-04-30 09:18:45
【问题描述】:

我有 2 个不同的页面,它们将显示相同的数据,并且它们都共享相同的组件。但是这两个页面的分辨率不同,一个是带有警告框的大小,一个是类似的 A4 大小。如何为它们设置动态高度和宽度。我尝试使用 ngstyle 不确定如何正确实现它 在普通的 html 中

<tbody class="classname" style="height: 60px; width: fit-content;"> 我添加了这个并且它可以工作,但是两个页面都采用相同的分辨率。

所以我用 ngstyle 再次尝试了同样的事情,两个页面都设置为相同的 60

[ngStyle]="{'height.px': 'Height' ? '60' : '200' }"

或者有没有使用 ngclass 的解决方案?

【问题讨论】:

  • 在什么条件下决定是哪个页面?
  • @Obaid 如果页面分辨率为 200,则应设置为 200 像素,反之亦然

标签: ng-class ng-style angularjs-ng-style


【解决方案1】:

因此,您的问题分为两个步骤。 一种是计算页面高度,这不是角度字段,而是特定于浏览器的问题。尽管浏览器确实公开了 clientHeightscrollHeight 属性,但是不同的浏览器对页面实际高度的理解方式存在差异。

因此最佳实践(著名的 jQuery 库也使用它)是获取不同的文档级高度属性并从中获取最大值。

您必须注入 DOCUMENT 常量才能将 DOM 文档访问到您的组件中。请查找以下示例角度组件代码。

import { Component, OnInit, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  public height = 0;

  constructor(@Inject(DOCUMENT) private document: any){
  }
  ngOnInit() {
    this.height = Math.max( this.document.body.scrollHeight, this.document.body.offsetHeight, 
                      this.document.documentElement.clientHeight, this.document.documentElement.scrollHeight, this.document.documentElement.offsetHeight );


  }

}

现在只需在 html 端,您就可以测试组件的 height 属性 并根据需要应用样式。有这样的想法..

<div [ngStyle]="{'height': height>=200 ? '200px' : '60px' }"></div>

谢谢。

【讨论】:

    猜你喜欢
    • 2016-07-17
    • 1970-01-01
    • 2022-12-14
    • 2016-07-14
    • 2021-11-14
    • 2022-06-10
    • 2018-05-02
    • 2018-08-28
    • 2018-08-23
    相关资源
    最近更新 更多