简体   繁体   中英

Angular update view after change data

<div class="text">{{message}}</div>

private message = 'Some message';

ngOnInit() {
    this.setMessageToDisplay();
}   

       setMessageToDisplay() {
          if (this.packageService.isDocPackageEmpty) {
                if(this.router.url === '/documents/todo') {
                    this.message = 'M1';
                }
                else if (this.router.url === '/documents/done') {
                    this.message = 'M2';
                }
                else if (this.imageService.isVisiblePatientDocList()) {
                    let pacientId = this.router.url.split("/")[2];
                    this.message = "M3";
                }
            } else {
                this.message = 'Def Message';
            }
            return this.message;
        }
    }

Using {{message}} displayed intialize value of this variable despite value changed in method this.setMessageToDisplay(). I do something like this in html <div class="text">{{setMessageToDisplay()}}</div> but method is executed few time and I want display only last value of message variable. Is possible set {{message}} in html and refresh view?

You can invoke change detection manually with ChangeDetecorRef module:

import {ChangeDetectorRef} from @angular/core

constructor(private ref:ChangeDetectorRef){}

ngOnInit() {
    this.setMessageToDisplay();
    this.ref.detectChanges();
}   

just try this change:

 <div class="text">{{message}}</div> public message = 'Some message'; ngOnInit() { this.message = this.setMessageToDisplay(); } setMessageToDisplay() { let message: string; if (this.packageService.isDocPackageEmpty) { if(this.router.url === '/documents/todo') { message = 'M1'; } else if (this.router.url === '/documents/done') { message = 'M2'; } else if (this.imageService.isVisiblePatientDocList()) { let pacientId = this.router.url.split("/")[2]; message = "M3"; } } else { message = 'Def Message'; } return message; } }

REMEMBER to set public your message

you can use:

this.ref.detectChanges();

or:

get message() { return this.setMessageToDisplay(); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM