Переменные в модальном ng-bootstrap не обновляются мгновенно

Проблема в том, что значения переменных (fileSize, filePath) не обновляются мгновенно, они обновляются только если я нажимаю на модальное окно.

Поскольку я использую электрон, я уже активировал обнаружение изменений с помощью метода detectChanges()

Но переменная обновляется только тогда, когда я нажимаю на модальное окно.

Вот код компонента

import { Component, OnInit , ViewChild , ElementRef, Output, EventEmitter, ChangeDetectorRef } from '@angular/core';
import { Http } from '@angular/http';

import { NgbActiveModal, NgbModal, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap'
import { ipcRenderer, remote } from 'electron';

@Component({
   selector: 'new-download-details',
   templateUrl: './new-download-details.html',
   styleUrls: ['./new-download-details.scss']
  })
export class NewDownloadDetails implements OnInit {

@ViewChild('newdownloaddetail') modal: ElementRef;
@Output() onAddDownload = new EventEmitter<FileModel>();

download_detail_modal : any;

url_d = '';
fileSize = 0;
fileName = '';
filePath = '';

constructor(public modalService: NgbModal, public httpService: Http, public cdrf: ChangeDetectorRef){

}

public ngOnInit() {

}

public showNewDownloadDetail(url: string){

    this.fileName = url.split('/').pop();        
    this.url_d = url;

    // send head request to electron
    ipcRenderer.send('download-prompt', url);
    ipcRenderer.on('download-prompt-detail',(event,data)=>{

            // getting file size 
            this.fileSize = data['content-length'] ;
            this.cdrf.detectChanges();
            console.log(this.fileSize);

    });

    this.download_detail_modal = this.modalService.open(this.modal);         

}


folderChoose(){
    console.log("folder chose");
    let dialog = remote.dialog;
    dialog.showOpenDialog({title: "Save File To ", 
                            properties: ['openDirectory', 'createDirectory'] },
                            (filePaths: string[])=>{
                                console.log("File Path : " + filePaths[0]);
                                this.filePath = filePaths[0];

                            }
                        );
}

addDownload(){
    this.onAddDownload.emit(new FileModel(this.url_d,this.fileName, this.filePath));
    this.download_detail_modal.close();
}
}

class FileModel{
  constructor(public url:string, public fileName:string, public filePath:string){

  }
}

Вот код для модального

      <!-- code for modal  -- >
     <!-- New Download Detail modal -->
     <ng-template #newdownloaddetail let-c="close" let-d="dismiss">
            <div class="modal-header">
                <h4 class="modal-title">Downloading</h4>
                <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">

                    <form>
                            <div class="container">
                              <div class="row">
                                  <div class="col-3">
                                    <div for="formGroupExampleInput">URL</div>
                                  </div>
                                  <div class="col-9">
                                    <input type="text" class="form-control" id="formGroupExampleInput" [(ngModel)]="url_d" name="url_d"  placeholder="{{ url_d }}">
                                  </div>
                              </div>
                              <div class="row">
                                    <div class="col-3">
                                      <div for="formGroupExampleInput">File Name</div>
                                    </div>
                                    <div class="col-9">
                                      <input type="text" class="form-control" id="formGroupExampleInput" [(ngModel)]="fileName" name="fileName"  placeholder="{{ fileName }}">
                                    </div>
                                </div>

                                <div class="row">
                                        <div class="col-3">
                                          <div for="formGroupExampleInput">Path</div>
                                        </div>
                                        <div class="col-9">
                                          <input type="text" class="form-control" id="formGroupExampleInput" (click)="folderChoose()" [(ngModel)]="filePath" name="filePath"  placeholder="{{ filePath }}">
                                        </div>
                                </div>
                            </div>
                          </form>
                    {{ fileSize | byteFormat  }}
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-outline-dark" (click)="addDownload()">Download</button>
              </div>
          </ng-template>

Скриншот модального окна до того, как я нажму на модальное окно

изображение перед нажатием на модальное окно

Скриншот модального окна после того, как я нажму на модальное окно

введите здесь описание изображения

Как вы думаете, в чем проблема?

РЕДАКТИРОВАТЬ: код для обновления переменных находится в showNewDownloadDetail()


person akshay    schedule 10.09.2017    source источник


Ответы (2)


Попробуй это :

addDownload(){
            this.onAddDownload.next(new FileModel(this.url_d,this.fileName, this.filePath));
            this.download_detail_modal.dismiss();
        }


this.download_detail_modal = this.modalService.open(this.modal)
            this.download_detail_modal.componentInstance.onAddDownload.subscribe((e) => {
                console.log('e', e);
            });     
person Chandru    schedule 10.09.2017
comment
Метод addDownload() не имеет значения. Он генерирует событие для загрузки файла в основной процесс электрона. - person akshay; 10.09.2017

Исправил с помощью NgZone

 ipcRenderer.on('download-prompt-detail',(event,data)=>{

        // use NgZone
        this.zone.run(()=>{

        this.fileSize = data['content-length'] ;

       }
});
person akshay    schedule 10.09.2017