Skip to content

Instantly share code, notes, and snippets.

@camilogiraldo
Last active February 28, 2019 04:22
Show Gist options
  • Save camilogiraldo/740a656b7e403bc255408a6982bcd62f to your computer and use it in GitHub Desktop.
Save camilogiraldo/740a656b7e403bc255408a6982bcd62f to your computer and use it in GitHub Desktop.
<form [formGroup]="form" (submit)="submitForm()">
<ng-template ngFor let-input [ngForOf]="formData">
<ng-container [ngSwitch]="input.controlType">
<ng-template [ngSwitchCase]="'text'">
<div class="form-group">
<label [for]="input.controlName"> {{input.controlName}}</label>
<input [formControlName]="input.controlName" [type]="input.valueType" [name]="input.controlName"
[required]="input.validators.required" [minlength]="input.validators.minlength"
[maxlength]="input.validators.maxlength" />
<div class="error" *ngIf="form.get(input.controlName).invalid &&
(form.get(input.controlName).dirty || form.get(input.controlName).touched)">
<div *ngIf="form.get(input.controlName).errors.required">Input required</div>
<div *ngIf="form.get(input.controlName).errors.minlength">Minimum length is {{input.validators.minlength}}</div>
</div>
</div>
</ng-template>
<!-- handling select & radio type inputs -->
<ng-template [ngSwitchCase]="'select'">
<div class="form-group">
<label [for]="input.controlName"> {{input.controlName}}</label>
<select [formControlName]="input.controlName" [name]="input.controlName" [id]="input.controlName"
[required]="input.validators.required">
<option value="">{{input.placeholder}}</option>
<option *ngFor="let option of input.options" [value]="option.value">{{option.optionName}}</option>
</select>
</div>
</ng-template>
<ng-template [ngSwitchCase]="'radio'">
<div *ngFor="let option of input.options" class="form-group row">
<input [formControlName]="input.controlName" [type]="input.controlType" [name]="input.controlName"
[value]="option.value" [required]="input.validators.required">
<label [for]="input.controlName"> {{option.optionName}}</label>
</div>
</ng-template>
</ng-container>
</ng-template>
<button type="submit" [disabled]="form.invalid">
Submit
</button>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment