Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In a template-driven form I have two inputs. The second one comes from a ng-template.

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

The inputTemplate looks like this:

<ng-template #inputTemplate>
    Last name <input type="text" name="lastName" [(ngModel)]="lastName" required> (required)
</ng-template>

Both inputs have 'required' attribute, but form gets valid although the second input is empty.

Is there a way to ensure the input from the template is recognized by the form?

Demo: Plunker

Edit: In my real application, ng-template comes from another (3rd party) component and is loaded using template reference, see this Plunker.

I only found some solutions regarding parent-child component problems, but these were not practicable in this case.

like image 934
fxmfr Avatar asked Nov 07 '17 10:11

fxmfr


2 Answers

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.

like image 101
Vlad Gheorghita Avatar answered Sep 23 '22 11:09

Vlad Gheorghita


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>
like image 42
Gray Young Avatar answered Sep 19 '22 11:09

Gray Young