【发布时间】:2017-05-14 08:52:34
【问题描述】:
我需要从服务器下载内容并将内容集成到我的 Nativescript/Angular2 应用程序中。内容提供者希望能够格式化文本。我使用过 HtmlView 和 WebView,它们有一些限制。
WebView 无法动态增长以适应内容的大小 以 StackLayout 为例。它创建了一个滚动区域 适合我们想要提供的用户体验。
HtmlView 有非常 对 HTML/CSS 格式的支持有限,尤其是在 Android 上。
<font color='green'>例如不起作用!
所以我开始研究动态生成 Angular2 组件。那就是从服务器下载模板。我一直在关注SO Answer 中的讨论,并取得了一些成功。 UI 是从运行时提供的简单字符串呈现的,是的!示例项目可以在 github 上找到,dynamic-demo。
为此,我更新了 NG 模板项目,如下所示:
@Component({
selector: "my-app",
templateUrl: "app.component.html",
})
export class AppComponent implements AfterViewInit {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(
@Inject('DynamicComponent') private _dynamicComponent: DynamicComponent
){};
ngAfterViewInit() {
this._dynamicComponent.addComponent(
this.container,
` <Label text="Hello, World!" class="h1 text-center"> </Label>
<Button text="Tap Again" (tap)="onTap()" class="btn btn-primary btn-active"> </Button>
`
)
}
public counter: number = 16;
public get message(): string {
if (this.counter > 0) {
return this.counter + " taps left";
} else {
return "Hoorraaay! \nYou are ready to start building!";
}
}
public onTap() {
this.counter--;
}
}
增强的核心是我添加的这个 DynamicComponent 类:
import { Injectable, Compiler, Component, NgModule, ViewContainerRef} from '@angular/core'
@Injectable()
export class DynamicComponent {
constructor(private compiler: Compiler) {}
public addComponent(container: ViewContainerRef, template: string) {
@Component({template: template})
class TemplateComponent {
onTap(args) {
console.log('onTap()');
}
}
@NgModule({declarations: [TemplateComponent]})
class TemplateModule {}
const mod = this.compiler.compileModuleAndAllComponentsSync(TemplateModule);
const factory = mod.componentFactories.filter((comp) =>
comp.componentType === TemplateComponent
);
const component = container.createComponent(factory[0]);
}
}
我想获得有关我的方法的一般反馈。
- 这行得通吗?
- 我是否需要担心原始 StackOverflow 讨论中较大答案的问题?
- 如何设置它,以便我可以提供轻击操作函数作为 DynamicClass 的输入,而不是像我所做的那样将它们嵌入到类中
onTap()?
【问题讨论】:
-
我们可以将它连接到formGroup吗??
标签: angular nativescript angular2-nativescript