Created
September 22, 2023 14:44
-
-
Save transcendr/344daaf1aae73f0d926901a61667e7b6 to your computer and use it in GitHub Desktop.
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
import { Component, OnInit, Input, ViewChild, ElementRef, HostListener } from '@angular/core'; | |
import { CommonModule } from '@angular/common'; | |
import { FormGroup, FormControl, Validators } from '@angular/forms'; | |
import { KratosUI, KratosNode } from '../../models/kratos.model'; | |
import { ReactiveFormsModule } from '@angular/forms'; | |
import { MaterialModule } from '../material.module'; | |
@Component({ | |
selector: 'swc-auth-registration-form', | |
standalone: true, | |
imports: [ | |
CommonModule, | |
ReactiveFormsModule, | |
MaterialModule, | |
], | |
templateUrl: './registration-form.component.html', | |
styleUrls: ['./registration-form.component.scss'], | |
}) | |
export class RegistrationFormComponent implements OnInit { | |
@Input() formData?: KratosUI; | |
@ViewChild('formElement') formElement!: ElementRef; | |
formGroups: { [key: string]: FormGroup } = {}; | |
objectKeys = Object.keys; | |
ngOnInit() { | |
if (this.formData) { | |
this.initializeFormGroups(this.formData); | |
} | |
} | |
initializeFormGroups(formData: KratosUI) { | |
const defaultGroup = new FormGroup({}); | |
formData.nodes.forEach((node: KratosNode) => { | |
if (node.group === 'default') { | |
this.createFormControl(node, defaultGroup); | |
} else { | |
if (!this.formGroups[node.group]) { | |
this.formGroups[node.group] = new FormGroup({}); | |
} | |
this.createFormControl(node, this.formGroups[node.group]); | |
// Add default controls to this group | |
Object.keys(defaultGroup.controls).forEach(key => { | |
this.formGroups[node.group].addControl(key, (defaultGroup.controls as any)[key]); | |
}); | |
} | |
}); | |
} | |
createFormControl(node: KratosNode, formGroup: FormGroup) { | |
const control = new FormControl( | |
node.attributes.value, | |
node.attributes.required ? Validators.required : null | |
); | |
if (node.messages.length > 0) { | |
control.setErrors({ 'customError': node.messages[0] }); | |
} | |
formGroup.addControl(node.attributes.name, control); | |
} | |
@HostListener('submit', ['$event']) | |
onSubmit(event: Event) { | |
event.preventDefault(); | |
event.stopPropagation(); | |
console.log('%c onSubmit', 'color: red', event); | |
// Find the form element and manually submit it | |
const form = event.target as HTMLFormElement; | |
// THIS IS LOGGED JUST BEFORE THE PAGE IS REFRESHED | |
console.log('%c form', 'color: red', { action: form.action, method: form.method, target: form.target }); | |
if (form.checkValidity()) { | |
form.submit(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment