我使用打字稿创建应用程序。现在我有麻烦了。使用来自服务器的 API 加载的模板不起作用,因为它在页面加载时作为网站的一部分加载时工作。我仍然不知道是因为它没有编译还是因为安全原因而出现问题。我试过 这个例子,但它仍然不起作用。这是我将后者应用于我的应用程序的方式:
简短描述:路由器调用 PageComponentLoader 调用 AppService 调用 PageComponent (不包括在内,因为它运行良好,所以假设没有问题)。后者调用 API 并插入(也清理)模板的答案。
问题:按钮按原样呈现<button>
,但不是<button md-button>MATERIAL</button>
。div
s 渲染,因为它也没有被flex
'ed。
app.module.ts
@NgModule({
imports: [
BrowserModule, FormsModule, HttpModule,
MaterialModule,
RouterModule.forRoot([
{ path: 'Page/:param', component: PageComponentLoader },
),
declarations: [AppComponent, DclWrapper, PageComponent, PageComponentLoader],
entryComponents: [PageComponent,PageComponentLoader],
bootstrap: [AppComponent]
dynamic.componets.loader.ts(取自链接中的示例)
// Helper component to add dynamic components
import { Component, ViewChild, Input, ViewContainerRef, Type, ComponentRef, ComponentFactoryResolver, Compiler } from '@angular/core';
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
// ,entryComponents: [PageComponent]
})
export class DclWrapper {
@ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
@Input() types: Type<Component>;
cmpRef: ComponentRef<Component>;
private isViewInitialized: boolean = false;
constructor(private componentFactoryResolver: ComponentFactoryResolver, private compiler: Compiler) { }
updateComponent() {
if (!this.isViewInitialized) {
return;
}
if (this.cmpRef) {
// when the `type` input changes we destroy a previously
// created component before creating the new one
this.cmpRef.destroy();
}
let factory = this.componentFactoryResolver.resolveComponentFactory(this.types);
this.cmpRef = this.target.createComponent(factory)
// to access the created instance use
// this.compRef.instance.someProperty = 'someValue';
// this.compRef.instance.someOutput.subscribe(val => doSomething());
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if (this.cmpRef) {
this.cmpRef.destroy();
}
}
}
应用服务.ts
import {Injectable } from '@angular/core';
@Injectable()
export class AppService {
component = {
title: 'Example',
type: PageComponent
}
getComponent() {
return this.component;
}
}
Page.component.loader.ts
@Component({
template: '<dcl-wrapper [types]="component.type"></dcl-wrapper>',
selector: 'Page',
providers:[AppService]
})
export class PageComponentLoader
component: {};
constructor(
private _appService: AppService) {
}
ngOnInit() {
this.component = this._appService.getComponent();
}
}
page.html
<div fxLayout="column">
<div [sanitizer]="myPage"></div>
</div>