[[oktatas:web:angular|< Angular]]
====== Angular Reaktív űrlap csoportosítással ======
* **Szerző:** Sallai András
* Copyright (c) 2025, Sallai András
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC BY-SA 4.0]]
* Web: https://szit.hu
===== Szükséges modulok =====
Szükségünk lesz a FormGroup és a ReactiveFormsModule-ra. A ReactiveFormsModule-t az imports részben is szerepeltetni kell.
import { FormGroup, ReactiveFormsModule } from '@angular/forms';
//...
imports: [ReactiveFormsModule],
//...
employeeForm!: FormGroup;
===== Bemenet =====
A form előkészítése:
ngOnInit() {
this.employeeForm = new FormGroup({
name: new FormControl(''),
city: new FormControl(''),
salary: new FormControl('')
});
}
===== Kattintás =====
onSubmit() {
console.log(this.employeeForm.value);
}
Kimenet:
{
"name": "Mari",
"city": "Pécs",
"salary": "391"
}
===== Teljes kód =====
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
standalone: true,
imports: [ReactiveFormsModule],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'app13';
employeeForm!: FormGroup;
ngOnInit() {
this.employeeForm = new FormGroup({
name: new FormControl(''),
city: new FormControl(''),
salary: new FormControl('')
});
}
onSubmit() {
console.log(this.employeeForm.value);
}
}
===== Érvényesség ellenőrzése =====
import { Component } from '@angular/core';
import {
FormControl,
FormGroup,
ReactiveFormsModule,
Validators
} from '@angular/forms';
@Component({
selector: 'app-employee',
standalone: true,
imports: [ReactiveFormsModule],
templateUrl: './employee.component.html',
styleUrl: './employee.component.css'
})
export class EmployeeComponent {
employeeForm!: FormGroup;
constructor() {}
ngOnInit() {
this.employeeForm = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(3)]),
city: new FormControl('', [Validators.required, Validators.minLength(3)]),
salary: new FormControl(0, [Validators.required, Validators.pattern('^[0-9]+$')])
});
}
onSubmit() {
if (this.employeeForm.valid) {
console.log('Form Submitted!', {
name: this.employeeForm.value.name,
city: this.employeeForm.value.city,
salary: this.employeeForm.value.salary
});
} else {
console.log('Form is invalid');
}
}
}