如何在Angular 2中获取ViewRef值

时间:2017-05-17 14:41:46

标签: javascript angular nativescript

所以我正在尝试在Angular2(和NativeScript)中构建一个动态表单。

到目前为止我所做的是:

  • 从REST API获取JSON
  • 将组件(通过模板)添加到ViewContainerRef

现在我想“提交”表格。为此,我想我可以简单地使用ViewContainerRef并获取它的“兄弟姐妹”(它们是基于之前提到的JSON动态创建的)并循环遍历它们并创建一个JSON对象来发布这个..但我不明白Angular2 DOM如何工作..

这是我到目前为止的(部分)代码:

添加组件功能

//... class DynamicComponent, has id and value properties
public addComponent(container: ViewContainerRef, template: string){
    @Component({template: template})
    class TemplateComponent{
        public value = "test";
    }

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

创建组件

@ViewChild("container",{ read: ViewContainerRef }) container : ViewContainerRef;
..

//foreach JSON element
let _component = <any>
    this._dynamicComponent.addComponent(
        this.container, elementObject.render()
    );
//the render() returns things like : `<Label text="foo"></Label>`
.. 

_component.prototype.onTap = () => {
    this.submit();
}

提交功能

submit(){
      let json=[];
      for(let i=0;i<this.container.length;i++){
        let component = this.container.get(i);
        //Ideally I want to do this:
        /*
          json.push({
            id:component.id,
            val:component.value
          });
        */
      }
}

基本上,我在提交函数中将“component”作为ViewRef对象,但是如何从那里继续?

另外,我对Angular2很新,所以这是正确的方法吗?我已经看过表单生成器,但我没有让它与动态创建的元素一起正常工作..

0 个答案:

没有答案
相关问题