How to get formControlName Programmatically in Angular 5 or above

35,937

Solution 1

from this input field to get formControlName

<input formControlName="item_name" #itemName (input)="inputChanged(itemName)">

You only need to get the attribute formControlName

inputChanged(element: HTMLElement) {
  log(element.getAttribute('formControlName')) // item_name 
}

Solution 2

Most straighforward way I've found:

HTML:

<input formControlName="item_name" (input)="inputChanged($event)">

TS:

inputChanged(e) {
  log(e.target.getAttribute('formControlName')) // item_name 
}

No need to add an id in every input. Just pass $event as parameter.

Solution 3

You can use that approach:

<input formControlName="item_name" #itemName (change)="inputChanged($event)">

When the input's value changes, the change event occurs, and Angular provides a corresponding DOM event object in the $event variable which this code passes as a parameter to the component's inputChanged() method.

inputChanged (event: any) { // without type info
this.myValue = event.target.value;
  }
}

Reference link: https://angular.io/guide/user-input

Another alternative more elegant:

template

<form [formGroup]="usersForm">
  <input type="text" formControlName="name" placeholder="name"/>
</form>

component class

export class AppComponent implements OnInit, OnDestroy {
  usersForm: FormGroup;
  message: string;

  private subscriptions$ = new Subscription();

  constructor( private formBuilder: FormBuilder) {}

  ngOnInit(): void {
    this.usersForm = this.formBuilder.group({
      name: '',
      age: '',
      gender: '',
    });

    this.subscriptions$.add(this.name.valueChanges.subscribe(value => {
      // Do someting
    }));
  }

  ngOnDestroy(): void {
    this.subscriptions$.unsubscribe();
  }

  get name(): AbstractControl {
    return this.usersForm.get('name');
  }
}

See the complete example in the Stackbliz:
https://stackblitz.com/edit/form-builder-example

Solution 4

You can get formControlName attribute using ElementRef

HTML Code

 <input formControlName="item_name" #itemName>

component Class file

import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';

export class AppComponent implements OnInit { 

    // itemName name is reference variable #itemName

    @ViewChild('itemName') itemName: ElementRef;

    ngOnInit() {
        this.itemName.nativeElement.getAttribute('formControlName');
    }
}

Get Change Value of formControllName

<input type="text" formControlName="item_name" #itemName (input)="inputChanged($event.target.value)">

   export class AppComponent {
    inputChanged(searchValue: string) {
    console.log(searchValue);
    }
}

Solution 5

If You are using Reactive Forms then instead of declaring formControlName in component template, you can create form in Component TS as follows:

 this.myForm= this.formBuilder.group({
      'item_name' : [null, Validators.compose([Validators.required])]
    });

Also, Instead of handling input changes through event, Reactive forms provide you privilege to handle input value changes by registering "value_changes" upon form field as follows:

this.myForm.get('item_name').valueChanges.subscribe(val => {
    this.formattedMessage = `My name is ${val}.`;
  });

In this way you always use the formControlName as defined in Reactive form Group in Component TS Definition.

It will be used in component template as follows:

<input formControlName="item_name" />
Share:
35,937
MWN
Author by

MWN

Updated on April 28, 2020

Comments

  • MWN
    MWN about 4 years

    Need to know, when you have a multiple controls in a form and you want to know to which control user changed so that you can take some actions.

    <input formControlName="item_name" #itemName (input)="inputChanged(itemName)">
    

    Why I need to get formControlName?

    as you can see in the image, some fields are edited but not confirmed that's why user sees options to verify or cancel the operation on that specific field. That's why I require to get formControlName of input-changed field so that I can display the options only to that field.

    enter image description here

    I have searched for its solution but couldn't found on stack-overflow that's why I decided to post this question with answer

  • MWN
    MWN about 6 years
    your method looks good to me. Can you share a detailed document or video link please.
  • Shubhi Sood
    Shubhi Sood about 6 years
    Yes you can find detailed documentation in following link: angular.io/guide/reactive-forms
  • Vince
    Vince almost 6 years
    Using a template reference variable is the simplest solution to match the simple src event html technic. angular.io/guide/template-syntax#ref-vars
  • Tarun Nagpal
    Tarun Nagpal over 5 years
    I want to get the formControlName. Is there any way to get in function "inputChanged" ?
  • Ricardo Ferreira
    Ricardo Ferreira almost 5 years
    if you see, I am using the "valueChanges" Observable from the "AbstractControl" class. This Observable returns the Value;
  • Ricardo Ferreira
    Ricardo Ferreira almost 5 years
    With this approach you know exactly which control has changed.
  • Dschuli
    Dschuli almost 4 years
    Not sure if its a question of Angular Version. I'm using Angular 9.2. I cannot find an attribute formControlName, but there is an attribute ng-reflect-name, which seems to be set to the fromControlName.
  • Dschuli
    Dschuli almost 4 years
    Note: Be aware that you will not have a formControlName attribute, when you set the formControlName as template variable, e.g. [formControlName]="xyz". Did cost me some time and headache to figure that out.