修改元素后如何刷新html元素

时间:2016-06-28 11:38:41

标签: html angular

我一直在尝试在修改html元素后进行打印,但元素尚未更改。 (Angular2) 这个源代码简化了一个。

<div *ngIf="displayType === 'screen'">
       <div>This is Screen</div>  
</div>
<div *ngIf="displayType === 'print'">
       <div>This is Print</div>  
</div>   

点击按钮时会发生以下事件。

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

但内容是修改前的元素。 我该如何刷新元素?

1 个答案:

答案 0 :(得分:0)

刷新触发更改检测所需的元素。 这是关于Angular 2中变化检测的非常好的帖子:http://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html

我在这里创建了一个plunker来说明它: http://plnkr.co/edit/0ZwkaQ776mKpLYZJogYx?p=preview

<button (click)="OnPrint()">OnPrint</button>

另外你不应该直接修改DOM元素,你应该创建一个组件并使用结构指令来显示它(这里组件有一个选择器“my-print”):

<my-print *ngIf="isPrint" [iframeSrc]="..."></my-print>