Changes don't propagate through the component

2019-01-27 09:37发布

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));

    }

}

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?

1条回答
Explosion°爆炸
2楼-- · 2019-01-27 10:10

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));
    }
}
查看更多
登录 后发表回答