'How to refresh html element after modifying element
I have been trying to print after modifying html element but element has not been changed. (Angular2) This source code is simplified one.
<div *ngIf="displayType === 'screen'">
<div>This is Screen</div>
</div>
<div *ngIf="displayType === 'print'">
<div>This is Print</div>
</div>
And when click a button the following event.
displayType: string = 'screen'; // default
OnPrint() {
this.displayType = 'print';
let tmp = document.createElement('div');
let el = this.elementRef.nativeElement.cloneNode(true);
tmp.appendChild(el);
let content = tmp.innerHTML;
let frame1 = document.createElement('iframe');
document.body.appendChild(frame1);
let frameDoc = frame1.contentWindow;
frameDoc.document.open();
frameDoc.document.write('<html><body>'+content+'</body></html>');
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
document.body.removeChild(frame1);
}, 500);
}
But contents are elements before modifying. How can I refresh elements?
Solution 1:[1]
To refresh the elements you need to trigger the change detection. Here is a very good post about change detection in Angular 2: http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html
I've created a plunker here to illustrate it: http://plnkr.co/edit/0ZwkaQ776mKpLYZJogYx?p=preview
<button (click)="OnPrint()">OnPrint</button>
Also you should not modify the DOM elements directly, you should create a component and use a structural directive to display it (here the component has a selector "my-print"):
<my-print *ngIf="isPrint" [iframeSrc]="..."></my-print>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pierre Urban |
