FireShock :
I want to generate HTML and open it in a new window to print. I have a component that should generates the HTML:
import { Component, ViewEncapsulation } from "@angular/core";
import { RelocateResponseVm } from "src/contracts/warehouse/relocateResponseVm";
@Component({
selector: 'transition-print',
styleUrls: ['./transition.component.scss'],
encapsulation: ViewEncapsulation.None,
templateUrl: './transition.print.component.html'
})
export class TransitionPrintComponent {
public data: RelocateResponseVm;
constructor() { }
}
Its template is:
<ng-container>
<div>
<h1>Operation №{{data.Id}}</h1>
<p>Date: <b>{{data.OperationDate}}</b></p>
<p>Name: <b>{{data.Name}}</b></p>
<p>Description: <b>{{data.Description}}</b></p>
</div>
</ng-container>
I create an instance of the component by the following code:
const componentFactory = this.resolver.resolveComponentFactory(TransitionPrintComponent);
let componentRef = componentFactory.create(this.injector);
componentRef.instance.data = relocateDoc;
console.log(componentRef.location.nativeElement);
Despite the relocateDoc
is filled the nativeElement
is empty:
<transition-print>
<!---->
<div>
<h1>Operation №</h1>
<p>Date: <b></b></p>
<p>Name: <b></b></p>
<p>Description: <b></b></p>
</div>
</transition-print>
What is the problem? How to fill the final HTML? Further I put it in a new window:
this.OpenWindow = window.open('', 'childwindow', 'width=800,height=400,left=150,top=200');
this.OpenWindow.document.body.innerHTML = "";
this.OpenWindow.document.body.appendChild(componentRef.location.nativeElement);
AlexanderFSP :
Good day!
You probably do the right things, but:
- You don't need
ng-container
, just remove it - Mark data as input property of
TransitionPrintComponent
(@Input() data;
) - Inject
ViewContainerRef
in your component, where you try to create an instance ofTransitionPrintComponent
. And try this code snippet:
const componentFactory = this.resolver.resolveComponentFactory(TransitionPrintComponent);
const componentRef = this.vcr.create(componentFactory);
componentRef.instance.data = relocateDoc;
console.log(componentRef.location.nativeElement);
Here the link, so you can get more details: https://angular.io/guide/dynamic-component-loader#resolving-components
Hope it helps ;)
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=376620&siteId=1