[Angular] Reactive forms - disabled attribute

문지은·2024년 5월 28일
0

Angular

목록 보기
2/4

문제 상황

Reactive Form을 사용하며 custom input 컴포넌트를 사용하고 있었는데, disabled 속성을 사용하자 콘솔창에 다음과 같은 경고가 발생하였다.

  It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
  when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
  you. We recommend using this approach to avoid 'changed after checked' errors.

  Example:
  // Specify the `disabled` property at control creation time:
  form = new FormGroup({
    first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
    last: new FormControl('Drew', Validators.required)
  });

  // Controls can also be enabled/disabled after creation:
  form.get('first')?.enable();
  form.get('last')?.disable();
  • Reactive Form 을 사용할 때는 disable 속성 또한 Reactive Form을 통해 설정하라는 뜻

해결 방법

  • 기존에 input 태그에 전달해주었던 disabled 속성 제거
<input formControlName="total" [disabled]="true"></input>
<input formControlName="total"></input>
  • 폼 컨트롤을 구성할 때 disabled를 true로 설정하면 실제로 DOM에 disabled 속성이 설정된다.
form = new FormGroup({
    ...
    total: new FormControl({ value: 0, disabled: true }, Validators.required),
  });
  • 컨트롤은 생성 후에도 활성화/비활성화할 수 있다.
form.get('first')?.enable();
form.get('last')?.disable();
  • custom input 태그를 사용했을 경우 ControlValueAccessor 를 통해 정의한 setDisabledState함수를 통해 disabled값을 가져온다.
disabled = signal<boolean>(false);

setDisabledState?(isDisabled: boolean): void {
  this.disabled.set(isDisabled);
}
<custom-input
  ...
  [disabled]="disabled()"
></custom-input>

References

Reactive forms - disabled attribute

profile
코드로 꿈을 펼치는 개발자의 이야기, 노력과 열정이 가득한 곳 🌈

0개의 댓글

관련 채용 정보