Iam trying to create a form which i can re-use by using ng-template. But somehow the data is not accessable in the component when I save the form and the function doAddMenuItem(postForm)
is called.
Here is the form with the ngTemplateOutlet
:
<form (submit)="doAddMenuItem(postForm)" #postForm="ngForm">
<ng-template [ngTemplateOutlet]="MsgRef"></ng-template>
<button class="button medium button__save">Save</button>
</form>
And the ng-template:
<ng-template #MsgRef>
<ul class="list">
<li>Titel:</li>
<li><input type="text" name="title" [(ngModel)]="menuItemObj.title"></li>
</ul>
<ul class="list">
<li>Symbol:</li>
<li><input type="text" name="symbol" [(ngModel)]="menuItemObj.symbol"></li>
</ul>
<ul class="list">
<li>Meer weten link:</li>
<li><input type="text" name="more_info_link" [(ngModel)]="menuItemObj.more_info_link"></li>
</ul>
<ul class="list">
<li>Bericht:</li>
<li>
<editor [init]="froalaOptions" name="text" [(ngModel)]="menuItemObj.text"></editor>
</li>
</ul>
</ng-template>
And the function in the component:
doAddMenuItem(formData) {
console.log(formData.value);
}
It seems NgForm is able to track controls only in nested templates.
To make it work you need to move #MsgRef template within form tag.
To make your controls really reusable I propose you to create custom form control by implementing ControlValueAccessor interface. So you will be able to use this custom control in any form:
Model:
MenuItem form control: