| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- import { Component, inject } from '@angular/core';
- import {
- FormBuilder,
- FormGroup,
- FormControl,
- FormArray,
- ReactiveFormsModule,
- Validators,
- } from '@angular/forms';
- import { ActivatedRoute, Router, RouterLink } 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 { Danka } from '../../models/danka';
-
- @Component({
- selector: 'app-danka-edit',
- imports: [AppHeader, AppSideMenu, ReactiveFormsModule, RouterLink],
- templateUrl: './danka-edit.html',
- styleUrl: './danka-edit.scss',
- })
- export class DankaEdit {
- danka: Danka | undefined;
-
- dankaForm = new FormGroup({
- householdName: new FormControl('鈴木家'),
- householder: new FormControl('鈴木 太郎'),
- postalCode: new FormControl('123-4567'),
- address: new FormControl('市内 1-2-3'),
- phones: new FormArray([
- this.createPhoneForm('03-xxxx-xxxx', '自宅'),
- this.createPhoneForm('090-xxxx-xxxx', '世帯主'),
- this.createPhoneForm('0584-xx-xxxx', '寺報連絡'),
- ]),
- });
-
- constructor(
- private dankaService: DankaService,
- private route: ActivatedRoute,
- private router: Router,
- ) {
- const id = this.route.snapshot.params['id'];
- if (id) {
- this.danka = this.dankaService.getDankaById(id);
-
- if (this.danka) {
- this.dankaForm.patchValue({
- householdName: this.danka.householdName,
- householder: this.danka.householder,
- postalCode: this.danka.postalCode,
- address: this.danka.address,
- });
-
- this.phones.clear();
-
- for (const phone of this.danka.phones) {
- this.phones.push(this.createPhoneForm(phone.tel, phone.note));
- }
- }
- }
- console.log(this.danka);
- }
-
- get phones() {
- return this.dankaForm.get('phones') as FormArray;
- }
-
- createPhoneForm(string = '', note = '') {
- return new FormGroup({
- tel: new FormControl(string),
- note: new FormControl(note),
- });
- }
-
- addPhone() {
- this.phones.push(this.createPhoneForm());
- }
-
- removePhone(index: number) {
- this.phones.removeAt(index);
- }
-
- saveDanka() {
- if (!this.danka) {
- return;
- }
-
- const formValue = this.dankaForm.value;
-
- const updatedDanka = {
- id: this.danka.id,
- householdName: formValue.householdName ?? '',
- householder: formValue.householder ?? '',
- postalCode: formValue.postalCode ?? '',
- address: formValue.address ?? '',
- phones: (formValue.phones ?? []).map((phone) => ({
- tel: phone.tel ?? '',
- note: phone.note ?? '',
- })),
- };
-
- this.dankaService.saveDanka(updatedDanka);
- this.router.navigate(['./danka-detail', this.danka.id]);
- console.log(this.dankaService.getDankaList());
- }
- }
|