* 영어표기가 디폴트, 이하 한글표기
https://angular.kr/guide/reactive-forms
0. FormGroup
- 반응형 폼
- view 의 내용이 변경될 때마다 감지 및 처리 가능
- 로그인, 회원가입 등에 사용시 용이
1. 사용법
0). app.module 에import 하기 (ReactiveFormsModule)
import { NgModule } from '@angular/core'; ... import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent, FormBuildTestComponent ], imports: [ BrowserModule, ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
1). 컴포넌트의 constructor 에 import 하기 (FormControl, FormGroup, FormBuilder)
- 변수 testForm 의 타입을 FormGroup 으로 정의하고 constructor 혹은 ngOnInit 에서 초기화한다.
- 초기화 하지 않으면 값이 꼭 있다고 선언해줘야 함 (testForm ! : FormGroup;)
- 템플릿과 폼 컨트롤을 연결하기 위해 HTML 에서 id 태그 활용
import { Component, OnInit } from '@angular/core'; import { FormBuilder,FormGroup } from '@angular/forms'; @Component({ selector: 'app-formBuildTest]', templateUrl: './formBuildTest.component.html', styleUrls: ['./formBuildTest.component.css'] }) export class FormBuildTestComponent implements OnInit { testForm: FormGroup; constructor(private formBuilder: FormBuilder) { this.testForm = this.formBuilder.group({ item: "", value: 0 }) } ngOnInit() { } submit(e?: any) { } } |
2). HTML 에 form 태그를 활용해서 formGroup 세팅하기
<form [formGroup]="testForm" (ngSubmit)="submit($event)"> <input type="text" formControlName="item"> <input type="text" formControlName="value"> <button type="submit">검색</button> </form> |
'프레임워크 > Angular' 카테고리의 다른 글
enum (0) | 2023.10.20 |
---|---|
pagination _(수정: 2023.11.13) (0) | 2023.09.12 |
Three.js (0) | 2023.01.16 |
Protocol, websocket, TCP, HTTP (0) | 2022.10.31 |
비동기 처리 (0) | 2022.10.25 |