ngControl formGroup 관계 angular form

agnusdei·2023년 10월 6일

1. 폼과 Angular

Angular 애플리케이션에서 폼을 다루는 것은 사용자 입력을 수집하고 처리하는 데 중요한 부분입니다. Angular는 폼 관련 작업을 쉽게 처리할 수 있도록 폼 모듈을 제공하며, 이를 사용하여 다양한 폼 컨트롤을 생성하고 관리할 수 있습니다.

2. 폼 그룹과 FormControl

Angular에서 폼을 사용할 때, 폼 그룹(FormGroup)과 폼 컨트롤(FormControl)은 핵심 개념입니다. 폼 그룹은 관련된 폼 컨트롤을 묶어서 관리하는데 사용되며, 폼 컨트롤은 개별 입력 요소를 나타냅니다.

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

// 폼 그룹 생성
const formGroup = new FormGroup({
  username: new FormControl(''),
  email: new FormControl(''),
  password: new FormControl('')
});

3. 폼 컴포넌트와 연결

폼 컨트롤을 HTML 템플릿과 연결하려면 formControlName 디렉티브를 사용합니다. 이 디렉티브를 사용하면 Angular가 폼 컨트롤과 템플릿을 연결하고 사용자 입력과 모델 데이터를 관리할 수 있습니다.

<form [formGroup]="formGroup">
  <input type="text" formControlName="username">
  <input type="email" formControlName="email">
  <input type="password" formControlName="password">
</form>

4. ngControl 인터페이스

ngControl 인터페이스는 Angular에서 폼 컨트롤을 추상화하는 인터페이스입니다. 각각의 폼 컨트롤은 ngControl을 구현하고 있으며, 이 인터페이스는 폼 컨트롤의 상태 및 값을 추적하고 유효성 검사를 수행합니다.

5. 폼 컨트롤 값 읽기 및 설정

ngControl을 사용하면 폼 컨트롤의 값을 읽고 설정할 수 있습니다. 폼 컨트롤의 현재 값을 얻으려면 ngControl.value를 사용하고, 값을 설정하려면 ngControl.setValue() 또는 ngControl.patchValue()를 사용할 수 있습니다.

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

@Component({
  selector: 'app-example',
  template: `
    <form [formGroup]="formGroup">
      <input type="text" formControlName="username">
      <button (click)="updateUsername()">Update Username</button>
    </form>
  `
})
export class ExampleComponent {
  formGroup: FormGroup;

  constructor() {
    this.formGroup = new FormGroup({
      username: new FormControl('JohnDoe')
    });
  }

  updateUsername() {
    const newUsername = 'NewUsername';
    this.formGroup.get('username').setValue(newUsername);
  }
}

6. ngControl과 컴포넌트 연결

ngControl은 컴포넌트와 함께 사용될 때 폼 컨트롤과 컴포넌트 간의 상호작용을 용이하게 만듭니다. 컴포넌트에서 ngControl을 사용하면 폼 컨트롤의 값을 읽고 변경할 수 있습니다.

import { Component } from '@angular/core';
import { NgControl } from '@angular/forms';

@Component({
  selector: 'app-username',
  template: '<input [ngModel]="ngControl.control?.value" (ngModelChange)="onInputChange($event)">'
})
export class UsernameComponent {
  constructor(public ngControl: NgControl) {}

  onInputChange(newValue: string) {
    // 폼 컨트롤 값이 변경될 때 수행할 로직
  }
}

위 코드에서 NgControl을 사용하여 컴포넌트와 폼 컨트롤을 연결하고, ngModel과 함께 사용하여 입력 요소와 폼 컨트롤 간의 값을 동기화합니다.

이제 Angular에서 폼을 사용하고 컴포넌트와 ngControl을 연결하는 기본 개념을 이해하셨을 것입니다. 이러한 기능을 활용하여 사용자 입력을 쉽게 수집하고 처리할 수 있습니다. 이러한 기능은 Angular의 강력한 폼 관리 기능 중 하나이며, 다양한 폼 요구사항을 처리하는 데 유용하게 사용됩니다.

0개의 댓글