깜놀하는 해므찌로

Ionic 기반 Angular form 활용 예시 / formGroup 본문

IT

Ionic 기반 Angular form 활용 예시 / formGroup

agnusdei1207 2023. 6. 11. 17:09
반응형
SMALL
<app-modal title="관리자 수정">
  <!-- 여기를 넣어야 헤드가 들어감 -->
  <ion-item>
    <form [formGroup]="adminForm" class="w-full h-full">
      <div class="flex flex-col text-gray-700 px-6 py-5 gap-2">
        <div class="flex flex-col gap-2">
          <ion-label for="name">이름*</ion-label>
          <ion-input
            formControlName="name"
            placeholder="10자 이하로 입력해주세요"
            maxlength="12"
            class="w-full rounded-md border border-gray-200"
          />
          <ion-label for="tel">연락처*</ion-label>
          <ion-input
            formControlName="tel"
            placeholder="숫자로만 입력해주세요"
            oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(/^(\d{0,3})(\d{0,4})(\d{0,4})$/, `$1-$2-$3`).replace(/\-{1,2}$/g, '');"
            maxlength="13"
            class="w-full rounded-md border border-gray-200"
          />
          <ion-label for="id">아이디*</ion-label>
          <ion-input
            formControlName="id"
            placeholder="15자 이하로 입력해주세요"
            maxlength="15"
            class="w-full rounded-md border border-gray-200"
          />
          <ion-label for="password">비밀번호*</ion-label>
          <ion-input
            formControlName="password"
            type="password"
            placeholder="20자 이하로 입력해주세요"
            maxlength="20"
            class="w-full rounded-md border border-gray-200"
          />
          <ion-label for="passwordConfirm">비밀번호 확인*</ion-label>
          <ion-input
            formControlName="passwordConfirm"
            type="password"
            placeholder="20자 이하로 입력해주세요"
            maxlength="20"
            class="w-full rounded-md border border-gray-200"
          />
        </div>

        <div class="flex flex-col py-2 gap-3">
          <div>관리자 권한 설정*</div>
          <div class="flex">
            <div *ngFor="let role of roles" class="flex">
              <label>{{role}}</label>
              <input
                (click)="handleRole(role)"
                class="accent-primary w-12 y-12 cursor-pointer"
                type="radio"
                [checked]="role === adminForm.controls['role'].value"
              />
            </div>
          </div>
        </div>

        <div class="border border-gray-200"></div>

        <div class="flex justify-end py-2 gap-1">
          <ion-button class="ion-cancel" (click)="dismiss()">취소</ion-button>

          <ion-button type="submit" class="ion-submit" (click)="submit()"
            >등록</ion-button
          >
        </div>
      </div>
    </form>
  </ion-item>
</app-modal>

0. 템플릿 코드

1. form 태그 활용

2. [fromGroup], (ngSubmit) 사용하기

3. ionic 기반은 'ion-' 시작하는 태그를 활용해야하며, input의 경우 label 이 필요합니다.

 

 

 

 

 

 

 

import { CommonModule } from '@angular/common';
import { Component, Input, OnInit } from '@angular/core';
import {
  FormGroup,
  FormControl,
  Validators,
  FormsModule,
  ReactiveFormsModule,
} from '@angular/forms';
import { IonicModule, ModalController } from '@ionic/angular';
import { InputTextComponent } from 'src/app/components/input-text/input-text.component';
import { InputRadioComponent } from 'src/app/components/input-radio/input-radio.component';
import { InputTelComponent } from 'src/app/components/input-tel/input-tel.component';
import { ModalComponent } from 'src/app/components/modal/modal.component';
import { ButtonComponent } from 'src/app/components/button/button.component';
import { InputPasswordComponent } from 'src/app/components/input-password/input-password.component';
import { ModalButtonComponent } from 'src/app/components/modal-button/modal-button.component';
import { Role, Admin } from 'src/lib/admin';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-update-admin',
  templateUrl: './update-admin.modal.html',
  styleUrls: ['./update-admin.modal.scss'],
  standalone: true,
  imports: [
    CommonModule,
    IonicModule,
    FormsModule,
    ReactiveFormsModule,
    InputTextComponent,
    InputRadioComponent,
    InputTelComponent,
    ModalComponent,
    InputPasswordComponent,
    ButtonComponent,
    ModalButtonComponent,
  ],
})
export class UpdateAdminModal implements OnInit {
  @Input() id!: string;

  roles: string[] = ['마스터', '매니저', '일반'];

  adminForm = new FormGroup({
    name: new FormControl<string>('', Validators.required),
    tel: new FormControl<string>('', Validators.required),
    id: new FormControl<string>('', Validators.required),
    password: new FormControl<string>('', Validators.required),
    passwordConfirm: new FormControl<string>('', Validators.required),
    role: new FormControl<string>('', Validators.required),
    updatedAt: new FormControl<Date>(new Date()),
  });
  constructor(private modalController: ModalController) {}
  ngOnInit(): void {
    const items = localStorage.getItem('admins');
    if (this.id && items) {
      let admins: Admin[] = JSON.parse(items);
      const admin = admins.find((admin) => admin.id === this.id);
      if (admin) {
        this.adminForm.patchValue(admin);
      }
    }
  }

  submit() {
    const item = this.adminForm.getRawValue(); // form value
    const items = localStorage.getItem('admins');
    if (items && item) {
      let admins: Admin[] = JSON.parse(items);
      const index = admins.findIndex((admin) => admin.id === item.id);
      if (index !== -1) {
        const body: Admin = {
          id: item.id ?? '',
          name: item.name ?? '',
          password: item.password ?? '',
          role: item.role as Role,
          position: admins[index].position,
          tel: item.tel ?? '',
          createdAt: admins[index].createdAt,
          updatedAt: item.updatedAt ?? new Date(),
        };
        admins[index] = body;
        localStorage.setItem('admins', JSON.stringify(admins));
      }
    }

    this.dismiss();
  }

  handleRole(role: string) {
    this.adminForm.controls['role'].setValue(role);
  }

  dismiss() {
    this.modalController.dismiss({
      id: this.id,
    });
  }
}

4. 컴포넌트

 

 

 

 

 

반응형
LIST