forms-demo.component.ts
angular/comprehensive-demo/src/app/features/dashboard/forms-demo/forms-demo.component.ts
/**
* Forms Demo Component
*
* Demonstrates both template-driven and reactive forms side by side.
*/
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, NgForm } from '@angular/forms';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-forms-demo',
standalone: true,
imports: [CommonModule, FormsModule, ReactiveFormsModule],
templateUrl: './forms-demo.component.html',
styleUrls: ['./forms-demo.component.scss']
})
export class FormsDemoComponent {
// Template-driven form data
templateForm = {
name: '',
email: ''
};
// Reactive form
reactiveForm: FormGroup;
constructor(private fb: FormBuilder) {
this.reactiveForm = this.fb.group({
name: ['', [Validators.required, Validators.minLength(2)]],
email: ['', [Validators.required, Validators.email]]
});
}
// Template-driven form submission
onSubmitTemplate(form: NgForm): void {
if (form.valid) {
console.log('Template form submitted:', this.templateForm);
alert('Template form submitted successfully!');
}
}
// Reactive form submission
onSubmitReactive(): void {
if (this.reactiveForm.valid) {
console.log('Reactive form submitted:', this.reactiveForm.value);
alert('Reactive form submitted successfully!');
} else {
Object.keys(this.reactiveForm.controls).forEach(key => {
this.reactiveForm.get(key)?.markAsTouched();
});
}
}
get name() {
return this.reactiveForm.get('name');
}
get email() {
return this.reactiveForm.get('email');
}
}
관련 글
server.js
server.js — javascript source code from the angular learning materials (angular/comprehensive-demo/server/server.js).
글 읽기 →app.component.ts
app.component.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/app.component.ts).
글 읽기 →app.config.ts
app.config.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/app.config.ts).
글 읽기 →app.routes.ts
app.routes.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/app.routes.ts).
글 읽기 →auth.guard.ts
auth.guard.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/core/guards/auth.guard.ts).
글 읽기 →role.guard.ts
role.guard.ts — typescript source code from the angular learning materials (angular/comprehensive-demo/src/app/core/guards/role.guard.ts).
글 읽기 →