【问题标题】:Access a DOM element from a helper class angular 6从帮助类 Angular 6 访问 DOM 元素
【发布时间】:2018-07-14 16:24:37
【问题描述】:

我有一个需要做一些 DOM 操作的小助手类。我试图在this 和其他一些人之后使用 ViewChild() 但它无法编译。我猜 ViewChild() 需要 @Component 指令才能工作?

我现在的班级是:

  @Injectable()
  export class calculator {

   constructor(){}

   calculate(calling_btn:string){

    //while a rather longish calcualtion is done, I need to disable the specific btn that called the calculate method. then display the result.

    @ViewChild(calling_btn) ele: ElementRef;
   }

html:

     <button #stage1 (click)="calculate('stage1')">Stage 1</button>

最多可以有 15 个按钮请求计算,我想禁用每个请求计算然后返回结果的按钮。它正在工作,但有时用户多次单击一个按钮,我想停止它。

如果我使用 getElementById 效果很好,但我读到它不是一个好习惯。有什么想法吗?

【问题讨论】:

  • 试试setTimeOut
  • 谢谢。可以多加几个字或者链接吗?
  • 查看此链接Demo 以获得更好的理解

标签: angular angular6


【解决方案1】:

首先,您有计算功能,这需要一段时间才能完成。
其次,您不希望用户在计算过程中与按钮交互

所以我认为解决这两个问题的简单方法是禁用按钮。

你的模板:

<button #stage1 (click)="calculate('stage1')" [disabled]="isCaculating">Stage 1</button>

你的组件,计算完后,我们再赋值isCaculating = false:

 @Injectable()
 export class calculator {
   isCaculating: boolean;
   constructor(){
   }

   calculate(calling_btn:string){
     this.isCaculating = true;
     //while a rather longish calcualtion is done, I need to disable the specific btn that called the calculate method. then display the result.
     this.isCaculating = false;
     @ViewChild(calling_btn) ele: ElementRef;
 }

我只是注意到您在计算时使用了按钮的字符串,所以我想可能会有多个按钮具有不同的字符串,例如“stag2”和“stage3”。

<button #stage1 (click)="calculate('stage1')" [disabled]="isCaculating['stage1']">Stage 1</button>


@Injectable()
 export class calculator {
   isCaculating: {};
   constructor(){
   }

   calculate(calling_btn:string){
     this.isCaculating[calling_btn] = true;
     //while a rather longish calcualtion is done, I need to disable the specific btn that called the calculate method. then display the result.
     this.isCaculating[calling_btn] = false;
     @ViewChild(calling_btn) ele: ElementRef;
 }

所以在您的组件内部,isCaculating 现在将成为一个对象,key 是您的按钮字符串,值将是 boolean 来决定我们是否在计算时禁用按钮。

希望这会有所帮助。

【讨论】:

  • 非常有前途的@lupa,让我试一试,然后回复你。谢谢。
猜你喜欢
  • 1970-01-01
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-11
  • 2011-05-31
  • 1970-01-01
相关资源
最近更新 更多