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;
<form [formGroup]="employeeForm"> </form>
<input type="text" class="form-control" id="name" formControlName="name"> <input type="text" class="form-control" id="city" formControlName="city"> <input type="text" class="form-control" id="salary" formControlName="salary">
A form előkészítése:
ngOnInit() { this.employeeForm = new FormGroup({ name: new FormControl(''), city: new FormControl(''), salary: new FormControl('') }); }
<form [formGroup]="employeeForm" (ngSubmit)="onSubmit()">
onSubmit() { console.log(this.employeeForm.value); }
Kimenet:
{ "name": "Mari", "city": "Pécs", "salary": "391" }
<form [formGroup]="employeeForm" (ngSubmit)="onSubmit()"> <div class="form-group"> <label for="name">Név</label> <input type="text" class="form-control" id="name" formControlName="name"> </div> <div class="form-group"> <label for="city">Település</label> <input type="text" class="form-control" id="city" formControlName="city"> </div> <div class="form-group"> <label for="salary">Fizetés</label> <input type="text" class="form-control" id="salary" formControlName="salary"> </div> <button type="submit" class="btn btn-primary">Felvesz</button> </form>
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); } }