問題:需要打印的模版特別多,而且各不相同,可能需要經常改動,如果在前端進行單獨創建組件的方式每次添加模版修改模版都要重新發布版本。
解決方式:通過把模版HTML保存到數據庫的方式,根據調用打印的傳參獲取不同的打印模版
oracle中nvarchar最多存4000個字符數量 NCLOB最大存儲大小為4gb
通過[innerHtml],只能渲染模版中的html語法和樣式,模版中的angular模版無法這些無法進行解析。這種方式只能渲染文本內容
通過ComponentFactoryResolver,這個對象可以接受一個組件類型創建一個組件實例。這種方式組件在前端需要存在
通過下面這種方式來動態編譯HTML模版
import {Compiler, Component, ComponentRef, Injector, NgModule, NgModuleRef, ViewChild, ViewContainerRef} from "@angular/core"; import {CommonModule} from "@angular/common"; import {RouterModule} from "@angular/router"; import { HelloComponent } from "./hello.component"; @Component({ selector: 'dynamic-template', template: `<h2>Stuff bellow will get dynamically created and injected<h2> <div #vc></div>` }) export class DynamicTemplateComponent { @ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef; private cmpRef: ComponentRef<any>; constructor(private compiler: Compiler, private injector: Injector, private moduleRef: NgModuleRef<any>, ) {} ngAfterViewInit() { this.createComponentFromRaw(`<div style="border: 1px solid blue; margin: 5px; padding: 5px"> <div>Start Raw Component ... </div> <h5>Binding value: {{data.some}}</h5> <span *ngIf="getX() === 'X'">Use *ngIf: {{getX()}} </span> </div>`); } private createComponentFromRaw(template: string) { const styles = []; function TmpCmpConstructor() { //需要給當前創建的模版傳遞的數據 this.data = { some: 'data' }; //需要給當前創建的模版傳遞的方法 this.getX = () => 'X'; } const tmpCmp = Component({ template, styles })(new TmpCmpConstructor().constructor); // Now, also create a dynamic module. const tmpModule = NgModule({ imports: [CommonModule], declarations: [tmpCmp], //如果這個html模版中用到了其他組件 需要把這個組件也傳遞進去 // declarations: [tmpCmp, HelloComponent], // providers: [] - e.g. if your dynamic component needs any service, provide it here. })(class {}); // Now compile this module and component, and inject it into that #vc in your current component template. this.compiler.compileModuleAndAllComponentsAsync(tmpModule) .then((factories) => { const f = factories.componentFactories[0]; this.cmpRef = f.create(this.injector, [], null, this.moduleRef); this.cmpRef.instance.name = 'my-dynamic-component'; this.vc.insert(this.cmpRef.hostView); }); } // Cleanup properly. You can add more cleanup-related stuff here. ngOnDestroy() { if(this.cmpRef) { this.cmpRef.destroy(); } } }
資料
https://stackblitz.com/edit/dynamic-raw-template?file=src%2Fapp%2Fdynamic-template.component.ts