I\'m trying to create a form builder using angular 2. An very basic example is as follows:
this.fields = [{name: \'Name\', type: \'text\'}, {name: \'Age\',
You can do this already if you wrap the content with a element.
// renders the template
// `item` is just an example how to bind properties of the host component to the content passed as template
@Directive({
selector: '[templateWrapper]'
})
export class TemplateWrapper implements OnChanges {
private embeddedViewRef:EmbeddedViewRef;
@Input()
private item:any;
constructor(private viewContainer:ViewContainerRef) {
console.log('TemplateWrapper');
}
@Input() templateWrapper:TemplateRef;
ngOnChanges(changes:{[key:string]:SimpleChange}) {
if (changes['templateWrapper']) {
if (this.embeddedViewRef) {
this.embeddedViewRef.destroy();
}
console.log('changes', changes);
this.embeddedViewRef = this.viewContainer.createEmbeddedView(this.templateWrapper, {item: this.item});
}
if (this.embeddedViewRef) {
console.log('context', this.embeddedViewRef.context);
this.embeddedViewRef.context.item = this.item;
}
}
}
// just some component that is used in the passed template
@Component({
selector: 'test-component',
styles: [':host { display: block; border: solid 2px red;}'],
directives: [TemplateWrapper],
template: `
test-comp
prop: {{prop | json}}
`
})
export class TestComponent {
@Input() prop;
constructor() {
console.log('TestComponent');
}
}
// the component the `` is passed to to render it
@Component({
selector: 'some-comp',
directives: [TemplateWrapper],
template: `
some-comp
`
})
export class SomeComponent {
constructor() {
console.log('SomeComponent');
}
@ContentChild(TemplateRef) template;
fields = [
{name: 'a', type: 'custom'},
{name: 'b', type: 'other'},
{name: 'c', type: 'custom'}];
}
// the component where the `` is passed to another component
@Component({
selector: 'my-app',
directives: [SomeComponent, TestComponent],
template: `
some content
item: {{item | json}}
`,
})
export class App {
constructor() {
console.log('AppComponent');
}
}
Plunker example