gpt4 book ai didi

来自 HTTP 调用的 Angular 动态模板

转载 作者:可可西里 更新时间:2023-11-01 16:59:16 27 4
gpt4 key购买 nike

我有一个简单的问题:在一个简单的 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

提前致谢

最佳答案

Angular 本身不支持动态模板。您可以使用延迟加载或直接通过 DOM 更新 View 。

... 或者有一个非常 hacky hack 来实现它,感谢 DenisVuyka:Full Article

这里我们需要创建 NgModule 来创建组件工厂,并使用组件装饰器将模板和提供者等元数据传递给组件类。

@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);
}
}

关于来自 HTTP 调用的 Angular 动态模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51891236/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com