【问题标题】:Angular create progress filling upload buttonAngular 创建进度填充上传按钮
【发布时间】:2017-11-11 02:22:58
【问题描述】:

我正在寻找自己的上传按钮,当文件上传时,背景将填充为绿色。有些事情我不知道该怎么做,在不直接使用 document.getElement 的情况下获取组件内部按钮的当前宽度。我需要对当前进度号进行计算以设置填充。最后,我需要将数据绑定到 css 属性以轻松更新 UI。

像这样的东西有Progress: number 的输入,当文件正在读取时,我将从另一个视图更新它。我不明白如何使用Progress 变量来实现this 之类的东西。

我的代码对我需要实现的步骤有一个非常清晰的定义,我不知道该怎么做的最大步骤是在不使用document.getElementById() 的情况下获取组件内部的<button>

我的基本观点:

<button [disabled]="Disabled" (click)="Clicked()" type="{{Type}}" class="btn btn-md spacing FakeClickable btn-info"><i class="fa fa-cloud-upload fa-lg"></i> {{Content}}</button>
<form>
    <input id="FileUpload-{{Content}}" [hidden]="true" type="file" name="file" (change)="FileReady($event)" />
</form>

该组件的 OnChange 事件: 更新 - 遵循此处链接的指南,但似乎没有任何反应。我正在更新正确的值,但没有任何反应。唯一发生的事情是背景颜色确实发生了变化,但没有填充。

ngOnChanges(changes: SimpleChanges)
  { 
    if (changes["Progress"] && changes["Progress"].currentValue != undefined)
    { 
      if (this.Progress != 100)
      {
        var thingy = this.fileBtn.nativeElement as HTMLButtonElement;
        // Remove the btn-info class from the button
        thingy.classList.remove('btn-info');
        // Get the current width of the button
        var curWidth = thingy.clientWidth;
        // Set the buttons background color to green
        //thingy.classList.add('btn-success');
        thingy.style.backgroundColor = "yellow";
        // Set the background fill percentage to Progress
        thingy.style.backgroundSize = `${this.Progress}% 100%`;
        thingy.style.backgroundPosition = `0 ${curWidth}px`;
      } else
      { 
        var thingy = this.fileBtn.nativeElement as HTMLButtonElement;
        thingy.classList.remove("btn-info", "btn-success");
        thingy.classList.add("btn-info");
        thingy.style.backgroundColor = "";
        thingy.style.backgroundSize = `${this.Progress}% 100%`;
        thingy.style.backgroundPosition = `0 ${curWidth}px`;
      }  
    }  
  }

【问题讨论】:

标签: javascript css angular


【解决方案1】:

如果您想访问组件类代码中的按钮,那么您正在寻找ViewChild。您的代码将如下所示:

<button [disabled]="Disabled" #uploadButton (click)="Clicked()" type="{{Type}}" class="btn btn-md spacing FakeClickable btn-info"><i class="fa fa-cloud-upload fa-lg"></i> {{Content}}</button>

这是您的模板,我们创建一个名为 uploadButton 的局部变量,然后使用 ViewChild 装饰器从我们的组件类中访问它:

import { ViewChild, ElementRef  } from '@angular/core';
// then:
@ViewChild('uploadButton') uploadButton: ElementRef;
ngOnChanges() {
   // this is how you access your button:
   this.uploadButton.nativeElement // do anything with it, this is just a usual HTML element reference
}

【讨论】:

  • 我刚刚开始走这条路,如果遇到任何障碍,我会发布任何更新。
  • 在这种情况下不建议使用这种方法。您最终将在需要此行为的每个组件中拥有按钮的逻辑。具有@Input 用于您当前进度的指令非常适合此用例。
猜你喜欢
  • 1970-01-01
  • 2022-08-23
  • 2018-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-06
  • 1970-01-01
  • 2019-08-16
相关资源
最近更新 更多