2016-12-30 47 views
0

我有要求从服务器下载内容并将内容集成到我的Nativescript/Angular2应用程序中。内容提供者希望能够格式化文本。我已经与HtmlView和WebView一起工作,并且他们有一些限制。为NativeScript动态生成Angular2组件

  1. web视图不能动态生长在 以适应内容的大小例如一个StackLayout。它创建了一个滚动区域,它不符合我们想提供的用户体验。

  2. HtmlView非常支持HTML/CSS格式,尤其是在Android上。例如 <font color='green'>不起作用!

所以我开始研究动态生成Angular2组件。即从服务器下载模板。我一直在关注SO Answer的讨论,并取得了一些成功。用户界面是从运行时提供的简单字符串呈现的,是啊!示例项目可在github上找到,dynamic-demoenter image description here

要做到这一点,我已经更新了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]); 
    } 
} 

我想得到我的方法的一般反馈。

  1. 这工作?
  2. 我是否需要担心原始StackOverflow讨论中较大的问题?
  3. 如何设置它,以便我可以提供该点击动作功能作为DynamicClass的输入,而不是像我在012xx与onTap()一样将它们嵌入到课程中?

回答

0

这里是我的问题3解决方案:

ngAfterViewInit() { 
    var component = <any> 
     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> 
     `); 

    component.prototype.onTap =() => { 
     this.counter++; 
    } 
} 

我更新addComponent返回动态创建的TemplateComponent类,然后我添加函数对象,我会在JS。有点丑但它的作品。