You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 10中如何将Form控制器名称及其值传递给函数?

Angular表单输入框失焦获取formControlName及值的实现方案

方式1:模板直接绑定事件(适合少量字段)

无需单独定义模板变量,直接通过$event对象读取属性即可,模板修改如下:

<mat-form-field appearance="outline">
  <mat-label>职位<span class="redColor">*</span></mat-label>
  <input 
    matInput 
    formControlName="Delegate_designation" 
    id="Delegate_designation" 
    placeholder="所属公司职位"
    (focusout)="passdataFunction($event.target.getAttribute('formControlName'), 你的表单组变量名.get($event.target.getAttribute('formControlName')).value)"
  >
</mat-form-field>

注意将代码中的你的表单组变量名替换为你组件中定义的FormGroup实例名
对应TS组件中的处理方法:

passdataFunction(controlName: string, value: any) {
  // 此处编写统一处理逻辑
  console.log('字段名:', controlName, '当前值:', value);
}

方式2:自定义指令统一挂载(适合大量表单字段场景)

如果表单字段数量多,逐个绑定事件效率低,可以通过自定义指令自动匹配所有带formControlName的输入框,实现全局失焦监听:

  1. 生成指令
ng g d directives/form-control-focusout
  1. 编写指令逻辑
import { Directive, HostListener, Output, EventEmitter } from '@angular/core';
import { FormControlName } from '@angular/forms';

@Directive({
  selector: '[formControlName]' // 自动匹配所有带formControlName的元素
})
export class FormControlFocusoutDirective {
  @Output() controlFocusout = new EventEmitter<{name: string, value: any}>();

  constructor(private control: FormControlName) { }

  @HostListener('focusout')
  onFocusOut() {
    // 方式一:直接调用全局公共服务的统一处理逻辑
    // this.commonService.passdataFunction(this.control.name as string, this.control.value);
    // 方式二:抛出自定义事件给对应组件单独处理
    this.controlFocusout.emit({name: this.control.name as string, value: this.control.value});
  }
}
  1. 在对应业务模块的declarations数组中注册该指令。如果选择事件抛出的方式,组件中按需监听即可:
<input formControlName="Delegate_designation" (controlFocusout)="passdataFunction($event.name, $event.value)">

内容的提问来源于stack exchange,提问作者Deepak Dev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 02:54:08