import { Component } from '@angular/core'; import { FormBuilder, FormGroup, ReactiveFormsModule, Validators, } from '@angular/forms'; import { ActivatedRoute, Router, } from '@angular/router'; import { AppHeader } from '../../share/header/app-header'; import { AppSideMenu } from '../../share/side-menu/app-side-menu'; import { DankaService } from '../../services/dankaService'; import { KakochoService } from '../../services/kakocho-service'; import { Danka } from '../../models/danka'; import { Kakocho } from '../../models/kakocho'; @Component({ selector: 'app-kakocho-edit', imports: [ AppHeader, AppSideMenu, ReactiveFormsModule, ], templateUrl: './kakocho-edit.html', styleUrl: './kakocho-edit.scss', }) export class KakochoEdit { danka?: Danka; kakocho?: Kakocho; kakochoForm: FormGroup; dankaId: string; constructor( private fb: FormBuilder, private dankaService: DankaService, private kakochoService: KakochoService, private route: ActivatedRoute, private router: Router, ) { // フォーム初期化 this.kakochoForm = this.fb.group({ name: ['', Validators.required], furigana: [''], relationship: [''], kaimyo: [''], deathDate: [''], ageAtDeath: [''], note: [''], }); // 檀家ID const dankaId = this.route.snapshot.params['dankaId']; this.dankaId = this.route.snapshot.params['dankaId']; if (dankaId) { this.danka = this.dankaService.getDankaById(dankaId); } // 編集対象ID const kakochoId = this.route.snapshot.params['kakochoId']; // 編集モード if (kakochoId) { this.kakocho = this.kakochoService.getKakochoById(kakochoId); if (this.kakocho) { this.kakochoForm.patchValue({ name: this.kakocho.name, furigana: this.kakocho.furigana, relationship: this.kakocho.relationship, kaimyo: this.kakocho.kaimyo, deathDate: this.kakocho.deathDate, ageAtDeath: this.kakocho.ageAtDeath, note: this.kakocho.note, }); } } } saveKakocho(): void { // form値取得 const formValue = this.kakochoForm.value; // 編集 if (this.kakocho) { const updatedKakocho: Kakocho = { ...this.kakocho, ...formValue, }; this.kakochoService.updateKakocho( updatedKakocho ); } else { // 新規追加 const newKakocho: Kakocho = { id: crypto.randomUUID(), dankaId: this.danka?.id ?? '', familyId: '', name: formValue.name, furigana: formValue.furigana, relationship: formValue.relationship, kaimyo: formValue.kaimyo, deathDate: formValue.deathDate, ageAtDeath: formValue.ageAtDeath, note: formValue.note, }; this.kakochoService.addKakocho( newKakocho ); } // 一覧へ戻る this.router.navigate([ '/danka-detail', this.danka?.id, ], { queryParams: { tab: 'kakocho' } }); } deleteKakocho(): void { if (!this.kakocho) { return; } this.kakochoService.deleteKakocho(this.kakocho.id); this.router.navigate(['/danka-detail', this.danka?.id], { queryParams: { tab: 'kakocho' } }); } cancelKakochoEdit() { this.router.navigate(['/danka-detail', this.danka?.id], { queryParams: { tab: 'kakocho' } }); } }