簡體   English   中英

如何在Angular中的自定義輸入組件上處理輸入事件?

[英]How to handle input events on custom input component in Angular?

我正在嘗試使用Angular 7 Reative Form創建一個自定義的Input組件,但是我無法將事件傳遞到輸入字段。

我的component有一個標簽,一個輸入字段和一個特定的布局。 我的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將能夠將這些事件“動態”傳遞到我的輸入字段。 有可能做到嗎?

諸如blur事件僅適用於input field ,不適用於<app-input-field>類的選擇器

您可以針對所有事件(例如模糊,摳像,鼠標懸停等)發出事件。

InputFieldComponent

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

工作演示

對於模糊事件,您需要創建一個具有相同名稱的事件發射器,並在輸入時發出此事件。

export class InputFieldComponent implements OnInit {

  @Output() blur:EventEmitter<any> = new EventEmitter(); // 👈

  constructor() { }

  ngOnInit() {
  }

}

模板

<input type="text" (blur)="blur.emit($event)"  >

app.template

<app-input-field (blur)="onBlur($event)" (keyup)="onKeyup($event)"></app-input-field>

我們對模糊事件進行了此操作,因為該事件不是冒泡的,因此在不創建任何自定義事件的情況下,鍵盤輸入將起作用,因為它會冒泡。

演示🔥🔥

您可以像這樣實現兩種方式的數據綁定

  @Input() value:EventEmitter<any> = new EventEmitter();

  @Output() valueChange:EventEmitter<any> = new EventEmitter();

模板

<app-input-field  [(value)]="name" ></app-input-field>

演示🌟🌟

您可以在元素本身上捕獲任何氣泡事件,例如input,keypress,keyup,keydown,也可以像處理模糊事件一樣處理它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM