So I'm trying to build a dynamic form in Angular2 (and NativeScript)..
What i've done so far is:
- Get JSON from REST API
- Add Component (via a template) to the ViewContainerRef
Now I want to "submit" the form. To do this, I thought I could simply use the ViewContainerRef and get its "siblings" (which are dynamically created based on the before mentioned JSON) and loop through them and create a JSON object to post this.. But I don't understand how the Angular2 DOM works..
Here is the (partial) code I've got so far:
addComponent function
//... 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;
}
Create Components
@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 Function
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
});
*/
}
}
Basically, I get "component" in the submit function as a ViewRef object, but how do I continue from there?
Also, I'm fairly new to Angular2, so is this the right way? I've seen the form builder but I didn't get it to work properly with dynamically created elements..