import { Component, OnInit } from '@angular/core';
import { Validators } from '@angular/forms';
import {
ActionEvent,
Button,
Dropdown,
FormStructure,
Input,
OptionChild,
RadioGroup
} from 'mat-dynamic-form';
@Component({
selector: 'app-conditional-form',
templateUrl: './conditional-form.component.html',
styleUrls: ['./conditional-form.component.scss']
})
export class ConditionalFormComponent implements OnInit {
formStructure: FormStructure;
constructor() {
this.formStructure = new FormStructure();
this.formStructure.title = 'Pet Owner Registration';
this.formStructure.appearance = 'outline';
this.formStructure.globalValidators = Validators.required;
this.formStructure.nodes = [
new Input('ownerName', 'Your Name').apply({
icon: 'person',
hint: 'Enter your full name'
}),
new Input('email', 'Email Address').apply({
icon: 'email',
validator: Validators.email
}),
new RadioGroup('hasPet', 'Do you have a pet?', [
new OptionChild('Yes', 'y'),
new OptionChild('No', 'n'),
]).apply({
selectedValue: 'n',
action: {
type: 'valueChange',
onEvent: (param) => this.onHasPetValueChange(param)
},
hint: 'Select whether you currently own a pet'
})
];
this.formStructure.validateActions = [
new Button('submit', 'Submit', {
onEvent: (param) => {
console.log('Form submitted:', param.structure?.getValue());
},
style: 'primary'
}).apply({
validateForm: true,
icon: 'send'
})
];
}
ngOnInit(): void {}
onHasPetValueChange(param: ActionEvent) {
// Define the pet-related fields to add
const petFields = [
new Dropdown('petType', 'Pet Type', [
new OptionChild('Dog', 'PD'),
new OptionChild('Cat', 'PC'),
new OptionChild('Bird', 'PB'),
new OptionChild('Other', 'PO')
]).apply({
hint: 'Select your pet type',
multiple: true
}),
new Input('breed', 'Pet Breed').apply({
hint: 'Enter the breed of your pet'
}),
new Input('petName', 'Pet Name').apply({
hint: 'What is your pet\'s name?'
})
];
if (param.event === 'y') {
// User selected 'Yes' - add pet fields after the hasPet field (position 3)
this.formStructure.createNodes(3, petFields);
} else {
// User selected 'No' - remove pet fields
this.formStructure.removeNodes(petFields);
}
}
}