Add Frontend
This commit is contained in:
64
frontend/src/app/components/item-form/item-form.ts
Normal file
64
frontend/src/app/components/item-form/item-form.ts
Normal file
@@ -0,0 +1,64 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
|
||||
import { ApiService } from '../../services/api';
|
||||
import { Item } from '../../models/item';
|
||||
import { MaterialModule } from '../../material.module';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
@Component({
|
||||
selector: 'app-item-form',
|
||||
templateUrl: './item-form.html',
|
||||
styleUrls: ['./item-form.scss'],
|
||||
standalone: true,
|
||||
imports: [MaterialModule, CommonModule, ReactiveFormsModule],
|
||||
})
|
||||
export class ItemFormComponent implements OnInit {
|
||||
itemForm: FormGroup;
|
||||
isEditMode = false;
|
||||
itemId: number | null = null;
|
||||
|
||||
constructor(
|
||||
private fb: FormBuilder,
|
||||
private apiService: ApiService,
|
||||
private router: Router,
|
||||
private route: ActivatedRoute
|
||||
) {
|
||||
this.itemForm = this.fb.group({
|
||||
name: ['', Validators.required],
|
||||
displayName: ['', Validators.required],
|
||||
target: ['', Validators.required],
|
||||
iconUrl: ['']
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
const idParam = this.route.snapshot.params['id'];
|
||||
if (idParam) {
|
||||
this.isEditMode = true;
|
||||
this.itemId = +idParam; // Convert string to number
|
||||
this.apiService.getItem(this.itemId).subscribe(item => {
|
||||
this.itemForm.patchValue(item);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
onSubmit(): void {
|
||||
if (this.itemForm.valid) {
|
||||
const itemData: Item = { id: this.itemId, ...this.itemForm.value };
|
||||
if (this.isEditMode) {
|
||||
this.apiService.updateItem(this.itemId!, itemData).subscribe(() => {
|
||||
this.router.navigate(['/']);
|
||||
});
|
||||
} else {
|
||||
this.apiService.createItem(itemData).subscribe(() => {
|
||||
this.router.navigate(['/']);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cancel(): void {
|
||||
this.router.navigate(['/']);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user