Template driven forms are model driven forms driven by directives in a template. Template driven forms are approached by angular JS users but sometimes template driven forms will be used for complex systems. For instance, if you want to dynamically set to validate a particular form filed you can use template driven forms. In the template driven forms uses two way data binding in terms of it uses ngModel despite formControl and fromGroups.
I am going to create a simple form that is able to create new form fields. The number of form-fields depends on the user. It can be changed at run time.
However, each form entry requires a name like formControlName in reactive forms and the state of the form as a whole that is a collection of individual form fields. Each form filed is assigned a unique id property. Therefore, template driven form controls need to be uniquely named. We can generate form fields using a unique control name. In this dynamic form, it has been used the current timestamp as a unique id or you can create a method to get random numbers to assign for this unique id. So it can get through with parent NgForm.
First, import formsModule to main module ex:- app.module.ts then create an interface to describe an object. You have to set some properties you want to this interface.
<form #parentForm="ngForm" (submit)="submitParentForm(parentForm)">
<ng-template ngFor let-form [ngForOf]="mainForm.formFields" let-index="index" let-isLast="last">
<input
type="form.formField1.type"
name="formFirld1_{{ form.id }}"
[(ngModel)]="form.formField1.value"
placeholder="form.formField1.placeholder"
required
/>
<div *ngIf="parentForm.submitted && !form.formField1.value">Form field 1 is required</div>
<input
type="form.formField2.type"
name="formFirld2_{{ form.id }}"
[(ngModel)]="form.formField2.value"
placeholder="form.formField2.placeholder"
required
/>
<div *ngIf="parentForm.submitted && !form.formField2.value">Form field 2 is required</div>
<button (click)="removeForm(index)">Remove form</button>
</ng-template>
<button type="submit">Submit</button>
<button type="button" (click)="parentForm.reset()">
Reset
</button>
</form>
<button (click)="addForm()" [disabled]="(!parentForm.form.valid)">Add new form</button>
#dynamic-form #angular-for-beginners #template-driven-form #angular