【问题标题】:Set component style from variable in Angular 2从Angular 2中的变量设置组件样式
【发布时间】:2016-11-02 23:56:43
【问题描述】:

我的目标是使用“styles”属性从组件变量中设置样式(在本例中为高度和宽度)。我认为有一个简单的数据绑定方法,但这可能是一厢情愿...

例如,如果我使用 html mustache 绑定,它可能如下所示:

@Component({
    selector: '[sidebar]',
    templateUrl: 'app/Nav/sidebar.comp.html',
    styles: [`
        .sidebar-nav {
            overflow: scroll;
            height: {{ height }};
        }
        .sidebar {
            height: {{ 0.9 * height }};
            width: {{ 0.21 * width }};
        }
    `]
})

export class SidebarComp {
    width: number;
    height: number;

    constructor() {
        this.height = window.innerHeight;
        this.width = window.innerWidth;
    }
}

显然这全错了,但我尝试了一些更可能的排列,但在 Angular 网站、Stack Overflow 或 Google 上找不到解决方案。我可能会减少使用 ngStyle 内联,但在这种情况下这并不理想。

【问题讨论】:

  • 你没有展示你想要的风格。 .sidebarSidebarComp 本身还是 sidebar.comp.html 内部的东西?

标签: html css angular


【解决方案1】:

就我而言,我需要在 px 和 % 单位之间更改图像样式动态切换。

所以我使用[ngStyle] 而不是[style.height.px]

我为谁担心。

HTML

<img [src]="imageUrl | safe: 'url'" [ngStyle]="{width: imagewidth, height: imageheight}">

TS

    if (this.properties.imageStyle == 'Stretch') {
      this.imagewidth = this.cols * this.unitWidth + 'px';
      this.imageheight = this.rows * this.unitHeight + 'px';
    }

    if (this.properties.imageStyle == 'Clip') {
      this.imagewidth = 100 + '%';
      this.imageheight = 100 + '%';
    }

https://stackblitz.com/edit/angular-image-clip-stretch

【讨论】:

    【解决方案2】:

    如果您使用百分比 (%),请尝试以下操作:

    <div class="sidebar-nav"   [style.height.%]="height">
    

    【讨论】:

      【解决方案3】:

      你可以设置宿主元素的样式

      @Component({
        selector: '[sidebar]',
        templateUrl: 'app/Nav/sidebar.comp.html',
        host: {
          '[style.height.px]':'0.9 * height',
          '[style.width.px]':'0.21 * width'
        }
      
      })
      
      export class SidebarComp {
          width: number;
          height: number;
      
          constructor() {
              this.height = window.innerHeight;
              this.width = window.innerWidth;
          }
      }
      

      和内容 (app/Nav/sidebar.comp.html) 一样

      <div class="sidebar-nav" [style.overflow]="'scroll'" [style.height.px]="height">
      

      <div class="sidebar-nav" [ngStyle]="{overflow: 'scroll', height: height + 'px'}">
      

      【讨论】:

      • 在 PsudoClass 中?
      • @AlejoNext 对不起,不明白你的意思
      • ::before如何编辑样式?在打字稿或javascript中
      • 我很确定不支持
      • @GünterZöchbauer 你在哪里找到这方面的文档?
      猜你喜欢
      • 2016-10-23
      • 2018-05-09
      • 2017-02-04
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 2015-12-27
      • 2018-03-26
      • 1970-01-01
      相关资源
      最近更新 更多