首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >打印角动态创建组件后不应用样式

打印角动态创建组件后不应用样式
EN

Stack Overflow用户
提问于 2022-03-29 04:41:33
回答 1查看 81关注 0票数 1

我已经运行了角9应用程序,并且通过动态创建组件来集成打印功能。打印功能按预期工作,但打印窗口打开时没有应用print-report.component.scss文件的css属性。

print.service.ts

代码语言:javascript
复制
@Injectable()
export class PrintService {

    constructor(
        private componentFactoryResolver: ComponentFactoryResolver,
        private injector: Injector
    ) { }

    showDialog(component) {
        const factory = this.componentFactoryResolver.resolveComponentFactory(component);
        
        const dialogComponentRef = factory.create(this.injector);
        dialogComponentRef.instance.title = 'Print page';
        
        dialogComponentRef.changeDetectorRef.detectChanges();

        //fetch the root DOM element of ModalComponent
        const domElement = (dialogComponentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
        
        const WindowPrt = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
        WindowPrt.document.write(domElement.innerHTML);
        WindowPrt.document.close();
        WindowPrt.focus();
        WindowPrt.print();
        WindowPrt.close();
    }

}

print-report.component.ts

代码语言:javascript
复制
@Component({
    selector: 'app-print-report',
    templateUrl: './print-report.component.html',
    styleUrls: ['./print-report.component.scss'],
    encapsulation: ViewEncapsulation.None
})
export class PrintReportComponent {

    @Input() title: string;    
}

print-report.component.html

代码语言:javascript
复制
<div class="name">{{title}}</div>

print-report.component.scss

代码语言:javascript
复制
.name { // these styles are not getting applied when print window opens
   color: red;
   font-weight: bold;
}

my-custom-component.ts

代码语言:javascript
复制
constructor(private printService: PrintService){}

onButtonClick(){
    this.printService.showDialog(PrintReportComponent);
}
EN

回答 1

Stack Overflow用户

发布于 2022-03-29 07:06:35

这里的问题是,您只是将HTML添加到新文档中。更快的解决办法应该是

代码语言:javascript
复制
showDialog(component) {
    const factory = this.componentFactoryResolver.resolveComponentFactory(component);
    
    const dialogComponentRef = factory.create(this.injector);
    
    dialogComponentRef.changeDetectorRef.detectChanges();

    //fetch the root DOM element of ModalComponent
    const domElement = (dialogComponentRef.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;
    
    const WindowPrt = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
    WindowPrt.document.head.innerHTML = document.head.innerHTML;
    WindowPrt.document.body.innerHTML = domElement.outerHTML;
    WindowPrt.document.close();
    WindowPrt.focus();
    WindowPrt.print();
    WindowPrt.close();
}

更好的解决方案应该是读取组件css文件并将其添加到头部。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71656544

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档