Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass a FormControl to a function from the template?

Let's say I have this:

<input formControlName="someName" (click)="onClick()">

I want my onClick function to be generic and set the value of the corresponding FormControl (the one I clicked).

How can I pass the concerned FormControl as a parameter of onClick?

I thought I could retrieve it from the control property of FormControlDirective or FormControlName but none of them have an exportAs attribute.

like image 568
Guerric P Avatar asked Mar 18 '20 18:03

Guerric P


People also ask

How do I get data from FormControl?

To fetch the value of a form control, we have to use value property on the instance of FormControl in our class. In the same way we can fetch the value in HTML template. city = new FormControl('Noida'); console. log(this.


4 Answers

I think this is what you want to achieve.

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);
  }
}
 <input
  appOnClickControl // use this to initialize directive
  (emitFormControl)="yourMethod($event)" // $event is the clicked form control
  formControlName="test"
></input>
like image 83
Satish Shr Avatar answered Oct 09 '22 23:10

Satish Shr


kinda repetitive but pretty sure you can only do this:

<input formControlName="someName" (click)="onClick('someName')">

then use someName on your form group to find the control

onClick(name: string) {
  const fc = this.form.get(name);
  // do whatever
}
like image 32
bryan60 Avatar answered Oct 09 '22 23:10

bryan60


In your html:

<input formControlName="someName" (click)="onClick($event)">

And then define your onClick function as:

onClick(event): void {
 alert(event.target.value)
}

Edit To get FormControl:

<input formControlName="someName" (click)="onClick(Form.get('someName'))">

and

onClick(formControl): void {
    formControl.setValue(someValue);
  }
like image 38
Sohail Aslam Avatar answered Oct 09 '22 22:10

Sohail Aslam


Not exactly sure what you're after, but try if the following works for you. It uses setValue() method to set values for the form. You can also use patchvalue if you want to set only partial values of the form.

Template

<form [formGroup]='groupedform' >
  <label>Name:  <br>
    <input type="text" formControlName='Name' required (mousedown)="onMouseDown(groupedform)"/>
  </label>
  <br>
  <br>
  <label>Email:  <br>
    <input type="email" formControlName='Email' required (mousedown)="setEmail(groupedform)"/>
  </label>
  <p>
  <button type="submit" [disabled]="!groupedform.valid" (click)="updateName()">Update Name</button>
  </p>
</form>

Component

export class AppComponent  {
   name = 'Angular';
   firstname = new FormControl('');
   groupedform = this.fb.group({
    Name : ['', Validators.required],
    Email: [],
  });

  constructor(private fb:FormBuilder) { }

  updateName() {
    console.log(this.groupedform.value);
  }

  onMouseDown(formControl: any) {
    this.groupedform.setValue({
      'Name': 'sample',
      'Email': '[email protected]'
    });
  }

  setEmail(formControl: any) {
    this.groupedform.patchValue({
      'Email': '[email protected]'
    });
  }
}

Working example: Stackblitz

like image 24
ruth Avatar answered Oct 09 '22 21:10

ruth