首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从助手类angular 6访问DOM元素

从助手类angular 6访问DOM元素
EN

Stack Overflow用户
提问于 2018-07-15 00:24:37
回答 1查看 370关注 0票数 0

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

我当前的类是:

代码语言:javascript
复制
  @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:

代码语言:javascript
复制
     <button #stage1 (click)="calculate('stage1')">Stage 1</button>

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

如果我使用getElementById,它工作得很好,但我看到它不是一个好的实践。有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2018-07-15 11:04:02

首先,您有calculate函数,它需要一段时间才能完成。

其次,您不希望用户在计算过程中与按钮进行交互

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

您的模板:

代码语言:javascript
复制
<button #stage1 (click)="calculate('stage1')" [disabled]="isCaculating">Stage 1</button>

您的组件,在计算后,我们将再次指定isCaculating = false:

代码语言:javascript
复制
 @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’。

代码语言:javascript
复制
<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,以决定我们是否在计算时禁用按钮。

希望这能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51341287

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档