Angular Forms (Simple)

2018. 10. 7. 19:43

프론트엔드 개발에서 Form은 필수적으로 사용됩니다.

로그인을 한다든지, 질문이나 댓글을 남기는 등 말이지요.


Angular 역시 Form을 쉽게 개발하도록 돕습니다.

데이터 바인딩, 유효성 검증, 에러 처리 관점에서요.

그럼 코드와 함께 보도록 하겠습니다.


0. Import ReactiveForms Module 


익숙한 과정이죠?

Angular의 모듈을 가져옵니다.

이번에는 Form에 관련된 모듈입니다.


app.module.ts 파일을 편집합니다.

import { FormsModule } from '@angular/forms';
...

@NgModule({
  ...
  imports: [
    ReactiveFormsModule,
... ], ... }) export class AppModule { }


1. Component ts 파일에 form control 추가


이제 컴포넌트 파일에 FormControl을 만들어줍니다.

html(템플릿)에 바인딩하기 위함입니다.

import { FormControl, FormGroup } from '@angular/forms';
...

@Component({
    ...
})
export class BudgetComponent implements OnInit {
    ...
    consumptionForm = new FormGroup({
        amount: new FormControl(''),
        desc: new FormControl('')
    });
    ...
}

보통 form은 여러개가 묶여있죠?

그룹핑 하기 위한 FormGroup도 사용하였습니다.



2. Template html에 form 태그 추가


말씀드렸듯이 html에 form을 추가하고 바인딩합니다.

fromGroup 속성에 컴포넌트의 FormGroup을 바인딩합니다.

익숙한 Property Binding이죠?

(http://dschci.tistory.com/81)

그리고 각각의 input에 FormControl을 할당해줍니다.

formControlName이라는 속성에 이름을 넣습니다.

저는 각각 amount, desc라고 명명했죠.

...
<form class="consumption-form" 
            (ngSubmit)="onSubmit()" 
            [formGroup]="consumptionForm">
  <mat-form-field>
    <input matInput
           formControlName="amount" 
           placeholder="Amount"
           type="text" required>
  </mat-form-field>
  <mat-form-field>
    <input matInput
           formControlName="desc" 
           placeholder="Description" 
           type="text">
  </mat-form-field>
  <button mat-raised-button color="primary" type="submit">Add</button>
</form>
...

material을 위한 태그와 속성은 없어도 동작합니다.

(mat-form-field, matInput)

그럼 이제 마지막으로 submit 동작을 정의해줍니다.


3. Component에 submit 로직 추가


위 html에 보면 submit 타입의 버튼이 있습니다.

그 버튼이 눌렸을 때의 동작입니다.

form의 ngSubmit에 바인딩이 있죠.

ngForm의 ngSubmit Event Binding입니다.

(http://dschci.tistory.com/83)

컴포넌트의 onSubmit 메서드와 연결되어있죠.


아래 코드입니다.

control에 입력된 값에 접근하는 방법입니다.

FormGroup이 컴포넌트에 정의되어있죠?

쉽게 아래와 같이 접근 가능합니다.

...
@Component({
    ...
})
export class BudgetComponent implements OnInit {
    ...
    onSubmit() {
        let amount: number = Number(this.consumptionForm.controls.amount.value)
        let desc: string = this.consumptionForm.controls.desc.value
        ...
    }
}

위는 간단한 바인딩을 통한 Form 사용이었습니다.

동작화면은 FormsModule 기능이 좀 더 사용되었습니다.


Angular Forms 동작 화면


다음에는 데이터 검증 및 에러 피드백에 대해서 써볼게요.


소스주소: https://github.com/jsrho1023/account-book

'IT Tech > Angular' 카테고리의 다른 글

Angular Router  (0) 2018.10.31
Angular Forms (Validation)  (0) 2018.10.14
Angular State Management (NGXS) Code  (0) 2018.09.22
Angular State Management (NGXS)  (0) 2018.09.15
Npm 거슬리는 pacakge-lock.json?  (2) 2018.09.02

TechTrip IT Tech/Angular