简体   繁体   中英

Access a DOM element from a helper class angular 6

I have a small helper class that needs to do a little DOM manipulation. I was trying to use ViewChild() following this and a few others but it can't compile. I am guessing ViewChild() requires @Component directive to work?

My current class is:

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

There can be maximum 15 buttons that will request calculation and I want to disable each button that requests calculation then return result. It is working but sometimes users click one button multiple times and I wanted to stop that.

It works well if I use getElementById but i read it is not good practice. Any idea?

First of all, you have the calculate function which will take awhile to be done.
Secondly, you don't want user to interact with button when the calculation is in progress

So I think the simple way to solve these 2 problems is that we will disable the button.

your temlplate:

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

your component, after the calculation, we will assign isCaculating = false again:

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

I just notice that you use the string for the button while calculating, so I guess so could have mutilple buttons with different string such as 'stag2' and '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;
 }

So inside your component the isCaculating now will be come an object, with the key is your button string and the value will be boolean to decide whether we will disable the button while calculating or not.

Hope this could help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM