如何将 FormControl 从模板传递给函数?

Twi*_*her 6 javascript angular angular-reactive-forms

假设我有这个:

<input formControlName="someName" (click)="onClick()">
Run Code Online (Sandbox Code Playgroud)

我希望我的onClick函数是通用的,并设置相应的值FormControl(我单击的函数)。

我如何将相关内容FormControl作为 的参数传递onClick?

我以为我可以从FormControlDirective或FormControlNamecontrol的属性中检索它,但它们都没有属性。exportAs

小智 5

我认为这就是您想要实现的目标。

import { Directive, HostListener, Optional, Output, EventEmitter } from '@angular/core';
import { NgControl, FormControl } from '@angular/forms';

@Directive({
  selector: '[appOnClickControl]' // if you want to target specific form control then use custom selector else you use can use input:
                                   // selector: 'input' to target all input elements
})
export class TestDirective {
  @Output() emitFormControl = new EventEmitter<FormControl>();

  constructor(@Optional() private formControl: NgControl) {
  }


  /**
   * If your only goal is to set value to the form control  then use this
   */
  @HostListener('click')
  onClick() {
    if (this.formControl) {
      this.formControl.control.setValue('test');
    }
  }

  /**
   * If you wanna pass the form control through the function you might use this
   */
  @HostListener('click')
  getFormControl(): void {
      this.emitFormControl.emit(this.formControl.control as FormControl);
  }
}
Run Code Online (Sandbox Code Playgroud)
 <input
  appOnClickControl // use this to initialize directive
  (emitFormControl)="yourMethod($event)" // $event is the clicked form control
  formControlName="test"
></input>
Run Code Online (Sandbox Code Playgroud)