How to get formControlName Programmatically in Angular 5 or above
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
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.
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
}