问题描述
我有一个组件的示例,当单击按钮时切换元素(div)。问题是第一次单击完全没有任何内容:更改根本不会传播,需要再次单击才能实现所需的行为。
I have the following example of a component that toggles an element (div) when a button is clicked. The problem is that the first click does absolutely nothing: the changes don't propagate at all and it is needed a second click to achieve the desired behaviour.
import { Component } from '@angular/core';
var exec = require('child_process').exec; //electron part
@Component({
selector: 'my-component',
template: `
<button (click)="showDiv()">Toggle Div</button>
<div *ngIf="show" style="width: 50px; height: 50px; background-color: green">
</div>
`
})
export class MyComponent {
private show = false;
public showDiv() {
exec("wmic logicaldisk get caption", function(error, stdout, stderr){
console.log(stdout);
this.show = !this.show;
}.bind(this));
}
}
所以棘手部分发生在我尝试执行Windows命令提示符命令时,即 wmic logicaldisk get caption
使用电子包并在命令返回其值后更新组件。
在使用电子复制某些文件的场景中( exec(copy a.txt dir,function(error,stdout,stderr){...})
)并且在操作结束后我的组件需要更新一些状态(假设:文件已成功复制!),此解决方案将无效。
那么这种方法可能出错?
So the tricky part happens when I try to execute a Windows command prompt command, i.e. wmic logicaldisk get caption
using electron packages and update the component after the command returns its values.
In a scenario where some files are being copied using electron (exec("copy a.txt dir", function(error, stdout, stderr){...})
) and after the operation ends my component needs to be updated with some status (let's say: Files copied successfully!), this solution won't work.
SO what could be wrong in this approach?
推荐答案
当我们改变角度以外的任何东西时,角度不考虑它。尝试使用ngZone(我不知道是否有效)
when we change anything out of angular, angular not take account of it. Try use ngZone (I don't know if work)
export class MyComponent {
private show = false;
constructor(private ngZone:NgZone) //<--ID NgZone
public showDiv() {
exec("wmic logicaldisk get caption", function(error, stdout, stderr){
console.log(stdout);
this.ngZone.run(()=>{
this.show = !this.show;
});
}.bind(this));
}
}
这篇关于更改不会通过组件传播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!