Set component style from variable in Angular 2

后端 未结 3 822
野性不改
野性不改 2020-12-17 15:21

My goal is to set a style (height and width in this case) from a component variable using the \"styles\" attribute. I would think there is a simple data binding method but t

相关标签:
3条回答
  • 2020-12-17 15:42

    In my case, I need change image style dynamic switch between px and % unit.

    So I use [ngStyle] instead of [style.height.px]

    I share for whom concern.

    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

    0 讨论(0)
  • 2020-12-17 15:47

    If you are using percent (%) try this :

    <div class="sidebar-nav"   [style.height.%]="height">
    
    0 讨论(0)
  • 2020-12-17 16:03

    You can style the host element like

    @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;
        }
    }
    

    and the content (app/Nav/sidebar.comp.html) like

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

    or

    <div class="sidebar-nav" [ngStyle]="{overflow: 'scroll', height: height + 'px'}">
    
    0 讨论(0)
提交回复
热议问题