【问题标题】:Angular2 Bind Attribute ValueAngular2绑定属性值
【发布时间】:2015-09-28 10:12:27
【问题描述】:

类似于Angular2 two-way data binding,我有一个父组件和一个子组件。在父组件中,我更改了通过属性传递给子组件的值。孩子的属性名为percentage

https://gist.github.com/ideadapt/59c96d01bacbf3222096

我想将属性值绑定到 html 属性值。喜欢:

。我没有找到任何有效的语法。所以我最终使用了一个更改监听器来进行一些手动 DOM 更新:
this.progressElement = DOM.querySelector(element.nativeElement, '.progress');
DOM.setAttribute(this.progressElement, "style", `width: ${this.percentage}%`);

有没有更优雅的方法来实现这一点?

【问题讨论】:

    标签: data-binding attributes angular


    【解决方案1】:

    您可以对 CSS 属性使用 百分比绑定[style.width.%]

    import {Component, Input} from 'angular2/core';
    
    @Component({
        selector: 'progress-bar',
        template: `
            <div class="progress-bar">
                <div [style.width.%]="value"> {{ value }}% </div>
            </div>
        `,
    })
    export class ProgressBar {
        @Input() private value: number;
    }
    

    【讨论】:

      【解决方案2】:

      使用NgStyle,其工作方式类似于Angular 1。由于alpha-30,NgStyle 在angular2/directives 中可用:

      import {NgStyle} from 'angular2/directives';
      

      然后在指令列表中包含NgStyle,这应该可以工作(here 是一些示例):

      @View({
          directives: [NgStyle]
          template: `
              <div class="all">
                  <div class="progress" [ng-style]="{'width': percentage + '%'}"></div>
                  <span class="label">{{percentage}}</span>
              </div>
          `
      })
      

      或者,不使用NgStyle,这也可以很好地工作:

      <div class="progress" [style.width]="percentage + '%'"></div>
      

      【讨论】:

      • 我们应该使用 [style.width.px] 或一些单位指示符
      猜你喜欢
      • 2016-08-18
      • 2017-04-28
      • 2016-12-04
      • 2018-05-23
      • 2019-04-12
      • 1970-01-01
      • 2015-07-11
      • 1970-01-01
      • 2016-12-10
      相关资源
      最近更新 更多