美文网首页我爱编程
Angular2打印组件essence-ng2-print的使用

Angular2打印组件essence-ng2-print的使用

作者: LuisWang | 来源:发表于2018-05-14 12:43 被阅读0次

关于Angular2中使用essence-ng2-print做打印功能
首先,需要下载essence-ng2-print

npm install --save essence-ng2-print
yarn add essence-ng2-print

上面两种下载方式随便选择一种就行

一、配置组件
在你需要打印功能的组件module中导入EssenceNg2PrintModule,
比如在main.module.ts中导入

import { EssenceNg2PrintModule } from "@node_modules/essence-ng2-print";
 @NgModule({
     imports: [
         EssenceNg2PrintModule
     ]
 })

二、在main.component.ts中配置相关属性

export class MainComponent implements OnInit {
  printCSS: string[];
  printStyle: string;
  printBtnBoolean = true;
  constructor() {
    this.printCSS = ['http://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css'];
    this.printStyle =
      `
      th, td {
        color: black !important;
     }
     `;
  }
  printComplete() {
    this.printBtnBoolean = true;
  }
  beforePrint() {
    this.printBtnBoolean = false;
  }
}

三、在html中使用组件

<table class="table table-bordered" #print>
  <thead>
    <tr>
      <th>名称</th>
      <th>城市</th>
      <th>邮编</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Tanmay</td>
      <td>Bangalore</td>
      <td>560001</td>
    </tr>
    <tr>
      <td>Uma</td>
      <td>Pune</td>
      <td>411027</td>
    </tr>
  </tbody>
</table>

<essence-ng2-print 
  [mode]="'popup'" 
  [popTitle]="'表格打印'" 
  [btnText]="'打印表格'" 
  [btnClass]="{'btn': true, 'btn-info': true}" 
  [printHTML]="print" 
  [printStyle]="printStyle" 
  [printCSS]="printCSS" 
  [showBtn]="printBtnBoolean" 
  (click)="beforePrint()" 
  (printComplete)="printComplete()">
</essence-ng2-print>

四、属性详解
model:打印模式,popup是以弹窗的形式打印
popTitle:打印页眉上显示文字,一般用于打印的描述信息
btnText:打印按钮上显示的文字
btnClass:打印按钮的样式
printHTML:打印的内容,告诉打印组件我要打印的是那个标签里面的内容,对应标签要添加#print属性
printStyle:打印的内容样式
printCSS:打印的内容样式,跟printStyle都是定义样式的,但是printStyle是自己写css,printCSS是引用外部css
showBtn:是否显示打印按钮,这种情况是把<essence-ng2-print></essence-ng2-print>放到要打印的div里面的时候,点击打印的时候需要把打印按钮隐藏,但是按我上面这种形式打印不需要考虑这个问题
click:angular2中的事件绑定,及点击打印的时候需要执行的代码
printComplete:打印完成之后需要执行的代码

五、关于是否显示打印按钮
我们在ts中定义一个布尔型的变量printBtnBoolean用来改变打印按钮的显隐,printBtnBoolean初始化为true,打印之前即click的时候改变为false,打印完成之后即printComplete的时候改为true,就可以完美的控制打印按钮的显示和隐藏。

六、总结,这些属性你并不一定都需要,比如我在实际应用中是这样用的

<essence-ng2-print 
  [mode]="'popup'" 
  [popTitle]="'表格打印'" 
  [btnText]="'打印表格'" 
  [btnClass]="{'btn': true, 'btn-info': true}" 
  [printHTML]="print" 
  [printCSS]="printCSS" 
</essence-ng2-print>

除了必要的属性之外,我不需要控制打印按钮的显隐,我不用自定义样式,直接引入bootstrap到printCSS就可以了。具体需求看个人情况。

相关文章

网友评论

    本文标题:Angular2打印组件essence-ng2-print的使用

    本文链接:https://www.haomeiwen.com/subject/quiddftx.html