Skip to content

Instantly share code, notes, and snippets.

@transcendr
Created September 22, 2023 14:43
Show Gist options
  • Save transcendr/3e76c0a197e48a1443160b49d73fdd35 to your computer and use it in GitHub Desktop.
Save transcendr/3e76c0a197e48a1443160b49d73fdd35 to your computer and use it in GitHub Desktop.
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] });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment