Angular Form Validation - How to include input from ng-template? Angular Form Validation - How to include input from ng-template? typescript typescript

Angular Form Validation - How to include input from ng-template?


You cannot do that as an ng-template does not support @Inputs and @Outputs. I suggest you create a custom input component. Implement the ControlValueAccessor to achieve this - it will let you bind ngModel, set value, etc.


Put ng-template#inputTemplate in the form, then it will work.

<form #testForm="ngForm">    First name <input type="text" name="firstName" [(ngModel)]="firstName" required> (required)    <br>    <ng-container *ngTemplateOutlet="inputTemplate"></ng-container>    <ng-template #inputTemplate>    Last name <input type="text" name="lastName" [(ngModel)]="lastName" required> (required)    </ng-template></form>


I believe the problem is in Angular dependency injection. Your template is defined elsewhere and it uses Injector from where ever it is defined. Your form cannot know about it and your input doesn't know about the form, even though it is above it in DOM — it is not in Injector tree. If you would have access to template you could pass the form directive as context and use it in template to link input and form.