首页 > 解决方案 > 如何在 Angular 中处理自定义输入组件上的输入事件?

问题描述

我正在尝试使用 Reative Form 创建自定义输入组件,Angular 7但我无法将事件传递给输入字段。

Mycomponent有一个标签和一个输入字段以及一个特定的布局。我的component html样子是这样的:

<div id="customInputGroup"  [formGroup]="parentFormGroup" [ngClass]="{'input-value': hasValue()}">
    <label [for]="inputId">{{label}}</label>
    <input [id]="inputId"  [name]="inputName"  class="form-control" [placeholder]="placeholder" [formControlName]="inputName" [mask]="mask">
</div>

我的Component

@Component({
  selector: 'app-input-field',
  templateUrl: './input-field.component.html',
  styleUrls: ['./input-field.component.css']
})
export class InputFieldComponent implements OnInit {


  @Input('placeholder') placeholder = '' ;
  @Input('label') label = '';
  @Input('inputId') inputId = '';
  @Input('inputName') inputName = '';
  @Input('parentFormGroup') parentFormGroup:FormGroup;
  @Input('mask') mask;
  constructor() { }

  ngOnInit() {
  }

  hasValue(){
    return (this.parentFormGroup.get(this.inputName).value != undefined 
    && this.parentFormGroup.get(this.inputName).value != null 
    && this.parentFormGroup.get(this.inputName).value != '')
  }

一切正常,直到我不得不处理一个输入onBlur事件(或者它可以是任何其他输入事件)。我想要的结果是调用我component传递这样的任何事件

<app-input-field (blur)="functionName()"></app-input-field>

或者

<app-input-field (keyup)="functionName()"></app-input-field>

component将能够“动态地”将这些事件传递给我的输入字段。有可能做到吗?

标签: htmlangularangular-reactive-formsangular2-custom-component

解决方案


blur作品这样的事件input field,而不是像这样的选择器<app-input-field>

您可以为所有事件发出事件,如模糊、按键、鼠标悬停等。

输入字段组件

HTML:

<input (blur)="functionName('blur')" (keyup)="functionName('keyUp')" [id]="inputId"  [name]="inputName"  class="form-control" [placeholder]="placeholder" [formControlName]="inputName" [mask]="mask">

TS:

@Output() OnInputEvent= new EventEmitter();

functionName(eventName) {
    this.OnInputEvent.emit(eventName);
}

在您的组件中:

<app-input-field (OnInputEvent)="functionName($event)"></app-input-field>

TS:

functionName(event) {
    switch (event) {
       case "blur":
       ...
       break;

       case "keyUp":
       ...
       break;
    }
}

工作演示


推荐阅读