[Angular] Directiveでリアクティブフォームの値を操作する


Directiveの中でリアクティブフォームを操作したい場面があると思います。
そんな時はNgControlをDIすればアクセスできます。

<form [formGroup]="formGroup">
  <input
    type="text"
    formControlName="hoge"
    hoge
  />
<form>
directive.ts
import { OnInit, Directive, ElementRef, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[hoge]'
})
export class HogeDirective implements OnInit {

  constructor(
    private ngControl: NgControl,
  ) {}

  get control() {
    return this.ngControl.control;
  }

  @HostListener('event', ['$event'])
  onHoge(event: any) {
    // リアクティブフォームへのアクセスが可能
    this.control.value;
    this.control.setValue('fuga');
  {
}