如何在 Angular 5 或更高版本中以编程方式获取 formControlName

How to get formControlName Programmatically in Angular 5 or above

需要知道,当您在一个表单中有多个控件并且您想知道用户更改了哪个控件以便您可以采取一些操作时。

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

为什么我需要获取 formControlName?

正如您在图片中看到的,一些字段已编辑但未确认,这就是为什么用户会看到用于验证或取消对该特定字段的操作的选项。这就是为什么我需要获取 formControlName 的输入更改字段,以便我可以只显示该字段的选项。

我已经搜索了它的解决方案,但在 stack-overflow 上找不到,这就是为什么我决定 post 这个问题的答案

从此输入字段得到formControlName

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

你只需要获取属性formControlName

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

如果您正在使用 Angular 响应式表单,您可以使用类似这样的东西

为你HTML输入

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

给你组件

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

formName: FormGroup;
myValue: string;

constructor(private formBuilder: FormBuilder) {}

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

    window.scroll(0,0);
}

inputChanged(){
    this.myValue = this.formName.get('item_name').value;
}

参考资料link: https://angular.io/guide/form-validation

您可以使用该方法:

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

当输入的值发生变化时,会发生 change 事件,并且 Angular 在 $event 变量中提供相应的 DOM 事件对象,此代码将其作为参数传递给组件的 inputChanged()方法。

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

参考资料link: https://angular.io/guide/user-input

另一个更优雅的选择:

模板

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

组件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');
  }
}

请参阅 Stackbliz 中的完整示例:
https://stackblitz.com/edit/form-builder-example

如果您使用的是响应式表单,则无需在组件模板中声明 formControlName,您可以在 Component TS 中创建表单,如下所示:

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

此外,响应式表单不是通过事件处理输入更改,而是通过在表单字段上注册“value_changes”为您提供处理输入值更改的特权,如下所示:

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

通过这种方式,您始终使用 formControlName,如 Reactive form Group in Component TS Definition 中所定义。

它将在组件模板中使用如下:

<input formControlName="item_name" />

您可以使用 ElementRef 获取 formControlName 属性

HTML代码

 <input formControlName="item_name" #itemName>

组件Class文件

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');
    }
}

获取 formControllName 的变化值

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

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

我发现的最直接的方法:

HTML:

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

TS:

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

无需在每个输入中添加 id。只需将 $event 作为参数传递即可。

像 FormGroup 和 FormControl 这样的响应式表单实例有一个 valueChanges 方法,该方法 returns 一个发出最新值的可观察对象。因此,您可以订阅 valueChanges 以更新实例变量或执行操作。

示例

myForm: FormGroup;
formattedMessage: string;

constructor(private formBuilder: FormBuilder) {}

ngOnInit() {
  this.myForm = this.formBuilder.group({
    name: '',
    email: '',
    message: ''
  });

  this.onChanges();
}

请注意我们在初始化表单后如何在 ngOnInit 生命周期挂钩中调用 onChanges 方法。这是我们的 onChanges 方法的内容:

onChanges(): void {
  this.myForm.valueChanges.subscribe(val => {
    this.formattedMessage =
    `Hello,

    My name is ${val.name} and my email is ${val.email}.

    I would like to tell you that ${val.message}.`;
  });
}

您还可以监听特定表单控件的更改,而不是整个表单组:

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