Custom Angular reactive form with SVG and clickable elements
hanneslim
Posted on January 1, 2022
During the Corona pandemic, many companies and employees discovered home office. As a result, it became apparent that not every employee required his own workstation. Instead, companies now offer a shared desk model. This means that employees flexibly share workstations. Often, you can reserve your desired workstation in advance. This workplace booking function has attracted me for some time. I find the possibility to create a Custom Reactive Form in Angular, which also includes an office plan, particularly interesting. In the Custom Angular Reactive SVG Form there is the possibility to select a workstation from the office plan and to mark it with a color. As soon as a workstation has been chosen, the form will be validated and the desk will be bookable. In the following the implementation is explained step by step.
We need the ReactiveFormsModule for the Reactive Angular Form SVG. Then we create a FormGroup and FormControl fields. I have named the FormGroup reservationForm. It contains a field for the name, a field for the weekday and a field for the place you want to book.
`public reservationForm: FormGroup = new FormGroup({
name: new FormControl('', [Validators.required], []),
weekday: new FormControl('', [Validators.required], []),
seat: new FormControl('', [Validators.required], []),
});`
To build a custom form field, the first thing we need is a new component. Here we can directly use a tip from Unleashed Design. Angular offers the possibility to include SVG images as templateUrl. We delete the seats.component.html and replace it with our SVG office plan named seats.component.svg. In the seats.component.ts we can replace the templateUrl with the SVG file:
selector: 'app-seats',
templateUrl: './seats.component.svg',
styleUrls: ['./seats.component.sass'],
We can already see our office plan in the Reactive Form, but it is still without functionality. To change that a ControlValueAccessor is needed. The ControlValueAccessor serves as an interface for a custom form control that integrates with Angular forms. The ControlValueAccessor asks for these four methods:
interface ControlValueAccessor {
writeValue(obj: any): void
registerOnChange(fn: any): void
registerOnTouched(fn: any): void
setDisabledState(isDisabled: boolean)?: void
}
This is the result:
If it is invalid:
Source code and more details to the project are on my blog: https://nerd-corner.com/how-to-build-a-custom-angular-reactive-svg-form-with-clickable-elements/
Posted on January 1, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.