我有一个小的helper类,需要做一些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,它工作得很好,但我看到它不是一个好的实践。有什么想法吗?
发布于 2018-07-15 11:04:02
首先,您有calculate函数,它需要一段时间才能完成。
其次,您不希望用户在计算过程中与按钮进行交互
因此,我认为解决这两个问题的简单方法是禁用按钮。
您的模板:
<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,以决定我们是否在计算时禁用按钮。
希望这能有所帮助。
https://stackoverflow.com/questions/51341287
复制相似问题