Last active
June 18, 2020 19:29
-
-
Save Trovin/d45e8c749bf5fb32278a422cf6e364a2 to your computer and use it in GitHub Desktop.
Angular - simple dynamic reactive form
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
INPUT DATA TO FORM | |
import { Validators } from '@angular/forms'; | |
export class InputData { | |
field: string; | |
icon: string; | |
validation: Validators[]; | |
errorMessage: string; | |
constructor(data: InputData) { | |
if (data) { | |
this.field = data.field; | |
this.icon = data.icon; | |
this.validation = data.validation; | |
this.errorMessage = data.errorMessage; | |
} | |
} | |
} | |
loginFormElements = [ | |
new InputData({ | |
field: 'username', | |
icon: 'fa fa-user-o', | |
validation: [Validators.required, Validators.minLength(2)], | |
errorMessage: 'incorrect username' | |
}), | |
new InputData({ | |
field: 'password', | |
icon: 'fa fa-user-o', | |
validation: [Validators.required, Validators.minLength(6)], | |
errorMessage: 'incorrect password' | |
}) | |
FORM METHODS | |
@Input() list: InputData[]; | |
form: FormGroup; | |
someItems = []; | |
constructor(private fb: FormBuilder) { } | |
ngOnChanges() { | |
!this.list || this.createForm(); | |
} | |
onSubmit() { | |
console.log(this.form.value); | |
} | |
private createForm() { | |
this.form = this.fb.group({ items: this.fb.array([]) }); | |
this.list.forEach(item => this.createItem(item.field, item.validation)); | |
} | |
get formItems() { | |
return this.form.get('items') as FormArray; | |
} | |
private createItem(field: string, validation: Validators[]) { | |
const control = { [field]: ['', validation] }; | |
this.formItems.push(this.fb.group(control)); | |
} | |
FORM HTML | |
<form | |
*ngIf="this.list" | |
(ngSubmit)="onSubmit()" | |
[formGroup]="form"> | |
<ng-container formArrayName="items"> | |
<div *ngFor="let item of formItems.controls; let i=index" [formGroupName]="i"> | |
<label for="i"> | |
<input | |
[id]="i" | |
[formControlName]="list[i].field" | |
[type]="list[i].field" | |
[placeholder]="list[i].field" /> | |
<i [class]="list[i].icon" aria-hidden="true"></i> | |
</label> | |
<div | |
*ngIf="item.invalid && item.touched" | |
role="alert" | |
class="error-message"> | |
{{list[i].errorMessage}} | |
</div> | |
</div> | |
</ng-container> | |
<button>submit</button> | |
{{form.value | json}} | |
</form> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment