我希望在我创建的模板中单击按钮上呈现一个模板作为单独的组件(自定义组件(,因为它可以多次使用。因此,当我单击时,要编译此自定义组件以作为HTML字符串返回,因为我需要使用字符串处理某些内容并发送HTML字符串。有可能使用角。
示例代码(只需解释我的案例(
import { templatecomponent } ./template.component
...
onButtonClick(): any
{
return compile(templatecomponent) // return the html from the template component
}
我认为您不能像上面一样使用它!您的组件和条件检查的选择器。您可以使用条件检查以单击按钮,如果您的组件将被称为
Custom.component.ts
@Component({
selector: "custom-app",
template: `I am from custom component`,
style: ""
})
Calling.component.ts
@Component({
selector: "calling-app",
template: `<button (click)="customFn()">Show custom</button>
<custom-app *ngIf="isCustom"></custom-app>
`,
style: ""
})
export class CallingComponent{
isCustom: false
constructor(){}
customFn(){
this.isCustom = !this.isCustom
}
}
不要忘记配置模块
我最近陷入了我需要将角组件的html解析为具有所有绑定和所有内容的字符串。
看来Angular并没有揭示完成此操作的方法。这是我为将组件HTML作为字符串解析的所做的。
app.component.html(查看所有文件的stackblitz链接(
import {
Component,
ComponentFactory,
ComponentFactoryResolver,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import { asyncScheduler } from 'rxjs';
import { PdfHtmlComponent } from './pdf-html.component';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
@ViewChild('pdfHtml', { read: ViewContainerRef }) container;
constructor(private resolver: ComponentFactoryResolver) {}
getPDFHtml() {
this.container.clear();
const factory: ComponentFactory<any> =
this.resolver.resolveComponentFactory(PdfHtmlComponent);
const componentRef = this.container.createComponent(factory);
componentRef.instance.title = 'Injected Title';
asyncScheduler.schedule(() => {
const htmlString = componentRef.location.nativeElement.innerHTML;
componentRef.destroy();
console.log('HTML STRING:', htmlString);
});
}
}
您可以在此处查看演示https://parse-angular-component-html-as-string.stackblitz.io
或者您可以在此处使用代码https://stackblitz.com/edit/parse-parse-angular-component-html-as-string?file=src/app/app/app/app.component.ts
愉快的编码!!!🎉🎉🎉
您可以创建一个将视图附加到自己的视图的渲染组件,然后返回内部HTML。
唯一的问题是,必须将组件渲染 ,因为必须将视图附加到DOM上,并且您必须使用 setTimeout()
允许子零件 time time time 完成渲染。
另外,您可以使用ngTemplate
参考而不是组件工厂。当您连接到ViewContainerRef
时,这两个基本相同。
这是我写的一个示例,但我没有尝试过:
@Component({
selector: 'app-render',
template: '',
styles: [
'position: absolute',
'top: -99999',
'left: -99999'
],
exportAs: 'appRender'
})
export class RenderComponent {
constructor(private view: ViewContainerRef,
private el: ElementRef<HTMLElement>) { }
public function compile(factory: ComponentFactory<any>): Promise<string> {
return new Promise(resolver => {
this.view.createComponent(template);
setTimeout(() => {
resolver(this.el.nativeElement.innerHTML);
this.view.clear();
});
});
}
}
您必须在应用程序中添加 <app-render>
组件,然后调用 compile(myComponent)
,然后返回使用html作为字符串的承诺。
如果您的 Child 组件使用*ngIf
或*ngFor
,则需要增加setTimeout()
的持续时间,或者您调用多个setTimeout()
功能。无论哪种方式,您都需要时间让HTML通过Angular渲染。
不可能采用不同的方法来创建同步函数,从而从组件作为字符串产生HTML。Angular不起作用。