2016-06-28 81 views
1

我一直试图在修改html元素后打印,但元素尚未更改。 (Angular2) 此源代码是简化的。如何在修改元素后刷新html元素

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

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

+0

这是什么目的。我无法理解这段代码。 Angular2不关心你动态添加的HTML。究竟应该更新什么? –

+0

我需要在打印时更改布局。这就是为什么我需要修改html。我提到了Angular2,以防人们不知道Angular2 – user3289230

回答

0

刷新您需要触发更改检测的元素。 这里是关于改变检测角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>