Yahya Uddin Yahya Uddin - 5 months ago 10
Node.js Question

Angular 2 is not update the UI when making changes to variable/model

I am currently using Angular 2 with Electron (which is basically using Node and web technologies to create a GUI).

All I want to do is list the files of the current directory.

Unfortunately, the variable "this.files" does not seem to update the data shown on the UI. Surprisingly however, when I click the dummy button thats linked to an empty method, it suddenly update. How do I fix this issue and whats the problem?

import {Component} from "@angular/core";
const fs = require('fs');

@Component(<any>{
selector: 'files',
template: `
<h2>Files</h2>

<ul *ngFor="let file of files">
<li>{{ file }}</li>
</ul>

<button (click)="showFiles">Show Files</button>
`,
})
export class FilesComponent {
files: any[];
cwd: string;

constructor() {}

ngOnInit() {
this.cwd = __dirname;
this.files = [];
this.loadFiles();
}

loadFiles() {
fs.readdir(this.cwd, (err, dir) => {
for (let filePath of dir) {
console.log(filePath);
this.files.push(filePath);
}
});
}

showFiles() {
// Empty method
// Shows the files for some reason despite nothing happening
}
}


Thanks for the help!

Answer

That's probably caused by fs.readdir. It seems it is using an API that is not patched by Angulars zone. To work around you can use

export class FilesComponent {
   constructor(private cdRef:ChangeDetectorRef) {}

   loadFiles() {
     fs.readdir(this.cwd, (err, dir) => {
        for (let filePath of dir) {
            console.log(filePath);
            this.files.push(filePath);
        }
        this.cdRef.detectChanges();
     });
   }
}
Comments