我有一个简单的问题:在一个简单的Angular组件中,我们可以动态更改通过http调用检索的模板吗?
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
/**
* Les liens link permettent de passer d'une page à l'autre.
*/
@Component({
selector: 'mycomponent',
template: '<strong>Loading…</strong>'
})
export class MyComponent implements OnInit {
//#region PROPRIÉTÉS
private moHttp : HttpClient
//#endregion
//#region CONSTRUCTEUR
constructor(poHttp: HttpClient){
this.moHttp = poHttp;
}
public ngOnInit(): void {
this.moHttp.get('https://myapiUrl').subscribe(poData:any => {
// here poData is HTML string, and I want to set it instead of the "<strong>Loading…</strong>"
});
}
}
//#endregion
提前谢谢
答案 0 :(得分:1)
Angular本身不支持动态模板。您可以使用延迟加载,也可以直接通过DOM更新视图。
...或者由于DenisVuyka:Full Article
在这里,我们需要创建NgModule来创建组件工厂,并使用Component装饰器将元数据(例如模板和提供程序)传递给组件类。
@Component({
selector: 'runtime-content',
template: `<div #container></div>`
})
export class RuntimeContentComponent {
constructor(public componentRef: ComponentRef, private compiler: Compiler){}
@ViewChild('container', { read: ViewContainerRef })
container: ViewContainerRef;
public compileTemplate(template) {
let metadata = {
selector: `runtime-component-sample`,
template: template
};
let factory = this.createComponentFactorySync(this.compiler, metadata, null);
if (this.componentRef) {
this.componentRef.destroy();
this.componentRef = null;
}
this.componentRef = this.container.createComponent(factory);
}
private createComponentFactorySync(compiler: Compiler, metadata: Component, componentClass: any): ComponentFactory<any> {
const cmpClass = componentClass || class RuntimeComponent { name: string = 'Denys' };
const decoratedCmp = Component(metadata)(cmpClass);
@NgModule({ imports: [CommonModule], declarations: [decoratedCmp] })
class RuntimeComponentModule { }
let module: ModuleWithComponentFactories<any> = compiler.compileModuleAndAllComponentsSync(RuntimeComponentModule);
return module.componentFactories.find(f => f.componentType === decoratedCmp);
}
}
答案 1 :(得分:0)
假设您的poData
是字符串,您可以执行以下操作
@Component({
selector: 'mycomponent',
template: '<div [innerHTML]="myContent"></div>'
})
export class MyComponent implements OnInit {
private moHttp : HttpClient;
myContent: any= '<strong>Loading…</strong>';
constructor(poHttp: HttpClient, private sanitizer: DomSanitizer){
this.moHttp = poHttp;
}
public ngOnInit(): void {
this.moHttp.get('https://myapiUrl').subscribe(poData:any => {
this.myContent = this.sanitizer..bypassSecurityTrustHtml(poData);
});
}
}
答案 2 :(得分:0)
尝试使用DomSanitizer
注意:您不必创建新字段即可保留注入的服务。
constructor(private http: HttpClient){}
将允许您在类中的任何位置使用httpClient(作为this.http
)。