2
3

More than 3 years have passed since last update.

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

Posted at

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');
  {
}
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3